React Native 获取:未定义不是一个对象
2020-03-25
1759
尝试在 React Native 中使用 fetch 并获取
Unable to symbolicate stack trace: Requiring module "node_modules\react-native\Libraries\Network\fetch.js", which threw an exception: TypeError: Attempted to assign to readonly property.
Unable to symbolicate stack trace: undefined is not an object (evaluating '_$$_REQUIRE(_dependencyMap[5], "../../Network/fetch").fetch')
这是我的代码
这是应用程序的第一个屏幕
import React, {Component} from 'react';
import {Text, View} from 'react-native';
export default class App extends Component {
state = {
loginURL:''
};
componentDidMount(): void {
fetch('http://10.0.2.2:4607/imgur/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
.then((response) => response.json())
.then((json) => {
if(json.type === 'redirect') this.setState({'loginURL': json.data});
});
};
render(){
return (<View><Text>Hello</Text></View>);
};
}
我尝试删除 node_modules 目录并重新运行
npm install
但问题相同。发生在模拟器上
我的 package.json 依赖项:
"dependencies": {
"@fortawesome/fontawesome-pro": "^5.13.0",
"@fortawesome/fontawesome-svg-core": "^1.2.28",
"@fortawesome/pro-light-svg-icons": "^5.13.0",
"@fortawesome/pro-regular-svg-icons": "^5.13.0",
"@fortawesome/pro-solid-svg-icons": "^5.13.0",
"@fortawesome/react-native-fontawesome": "^0.2.3",
"@react-native-community/masked-view": "^0.1.7",
"@react-navigation/drawer": "^5.3.4",
"@react-navigation/native": "^5.1.3",
"appcenter": "3.0.0",
"appcenter-analytics": "3.0.0",
"appcenter-crashes": "3.0.0",
"react": "16.9.0",
"react-native": "0.61.5",
"react-native-gesture-handler": "^1.6.1",
"react-native-reanimated": "^1.7.1",
"react-native-render-html": "^4.2.0",
"react-native-safe-area-context": "^0.7.3",
"react-native-screens": "^2.4.0",
"react-native-svg": "^11.0.1",
"react-native-vector-icons": "^6.6.0",
"react-native-webview": "^8.2.1",
"react-navigation": "^4.3.3"
},
2个回答
因此,当我启用调试器模式时,我收到了进一步的错误
TypeError: Cannot assign to read only property 'forEach' of object '#<Headers>'
TypeError: Cannot read property 'fetch' of undefined
Error: Requiring module "node_modules\react-native\Libraries\Network\fetch.js", which threw an exception: TypeError: Cannot assign to read only property 'forEach' of object '#<Headers>'
在模块上,我包含了一个 forEach polyfill 来循环并像数组一样处理对象。例如:
if (!Object.prototype.forEach) {
Object.defineProperty(Object.prototype, 'forEach', {
value: function (callback, thisArg) {
if (this == null) throw new TypeError('Not an object');
for (let key in this) {
if (this.hasOwnProperty(key)) callback.call(thisArg, this[key], key, this);
}
}
});
}
当我删除此代码时,一切都按预期工作!我找不到负责引发异常的代码,但至少我知道原因是我自己的代码 :)
TheBritishAreComing
2020-03-26
这可能无关紧要,但你为什么在 setState 上使用引号? 不应该是这样的:
this.setState({'loginURL': json.data});
应该是这样的:
this.setState({loginURL: json.data});
Filip F.
2020-03-25