我正在处理以下令人沮丧的错误:
Home.js:231 未捕获( promise 中)TypeError: _this9.setState 不是函数。错误来自以下函数的最后一行:
checkIfRunning() {
return fetch('/api/following/iscurrentlyrunning', {
credentials: 'include',
})
.then(response => {
console.log(response.status);
if (response.status === 200) {
return response.json();
}
})
.then(response => {
let cState = this.state;
cState.running = response;
this.setState(cState);
});
}
我确实在组件构造函数中绑定(bind)了该函数,当我单独调用它时,它工作正常。当我尝试调用计时器(setInterval)中的函数时,出现了问题。在 componentWillMount 中,我调用了几个函数:
componentWillMount() {
this.checkIfFirstTimeLogin()
.then(() => {
// user already exists
if (!this.state.firstLogin) {
this.Name();
this.getRole();
setInterval(() => this.checkIfRunning(), 10000);
}
})
.then(() => {
let cState = this.state;
cState.pageLoading = false;
this.setState(cState);
})
.catch(error => console.log(error));
}
我有一种直觉, promise 链由于我目前不明白的原因而打破了绑定(bind)。
感谢您的帮助,
最佳答案
Promise 是有保证的 future ,这意味着一旦调用整个 Promise 链就会触发,并且您几乎无法阻止它。
在实际层面上,这意味着您需要检查以确保您的组件实例在尝试访问组件实例之前仍然已安装,因为组件可能在此 promise 链完成之前已卸载。
.then(response => {
...code here...
// important! check that the instance is still mounted!
if (this.setState) {
this.setState(cState);
}
});
此外,您永远不应该像在这里所做的那样直接改变本地状态:
// don't mutate state directly, use setState!
let cState = this.state;
cState.running = response;
关于javascript - ReactJS:未捕获( promise 中) this.setState 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51144701/