[英]undefined this.setState inside 'then' block
I have the following function, this.setState
is usable outside of the .then
method.我有以下
.then
,this.setState 在this.setState
方法之外可用。
autoWork(e) {
this.setState({ showWaiting: true });
actions.autoSubmit(exampleVarOne, exampleVarTwo).then(function (results) {
dbAction.fetch().then(response => {
if (response.status === 200) {
const responseData = response.data;
this.setState({ disabledButton: true })
this.setState({ showWaiting: false });
}
}).catch(function (error) {
console.log(error);
this.setState({ showWaiting: false });
});
});
}
However I get the following error但是我收到以下错误
Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined
未捕获(承诺中)类型错误:无法读取未定义的属性“setState”
for this line of code this.setState({ disabledButton: true })
对于这行代码
this.setState({ disabledButton: true })
this
is not accessible inside the then
block? this
then
块内无法访问? How can I update the state inside the then
block?如何更新
then
块内的 state?
Yes, that's because function
's can set their own this
context.是的,那是因为
function
可以设置自己的this
上下文。 You can easily avoid that by using an arrow function instead:您可以通过使用箭头 function 来轻松避免这种情况:
Change:改变:
actions.autoSubmit(exampleVarOne, exampleVarTwo).then(function (results) {
to至
actions.autoSubmit(exampleVarOne, exampleVarTwo).then((results) => {
ECMAScript 6 introduced arrow functions, In your case, the anonymous function would not able to access " this " until it bound. ECMAScript 6 引入了箭头函数,在您的情况下,匿名 function 在绑定之前无法访问“ this ”。 They don't have their own this binding.
他们没有自己的 this 绑定。 Instead, this is looked up in scope just like a normal variable.
相反,它在 scope 中查找,就像普通变量一样。
You need to add arrow function at first " .then " and as well as in " .catch "您需要首先在“ .then ”和“ .catch ”中添加箭头 function
autoWork(e) {
this.setState({ showWaiting: true });
actions.autoSubmit(exampleVarOne, exampleVarTwo).then((results) => {
dbAction.fetch().then((response) => {
if (response.status === 200) {
const responseData = response.data;
this.setState({ disabledButton: true })
this.setState({ showWaiting: false });
}
}).catch((error) => {
console.log(error);
this.setState({ showWaiting: false });
});
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.