reactjs - undefined this.setState inside 'then' 块
问题描述
我有以下功能,this.setState
可以在.then
方法之外使用。
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 });
});
});
}
但是我收到以下错误
未捕获(承诺中)类型错误:无法读取未定义的属性“setState”
对于这行代码this.setState({ disabledButton: true })
this
在块内无法访问then
?如何更新then
块内的状态?
解决方案
是的,那是因为function
's 可以设置自己的this
上下文。您可以通过使用箭头函数轻松避免这种情况:
改变:
actions.autoSubmit(exampleVarOne, exampleVarTwo).then(function (results) {
到
actions.autoSubmit(exampleVarOne, exampleVarTwo).then((results) => {
推荐阅读
- google-chrome-extension - Timestamp in chrome extension notification
- html - 如何避免在可折叠面板内提交表单时重新加载页面?
- entity-framework - 不使用迁移时实体框架的优点
- angular - 在角度应用程序中获取 [Object Object]
- php - sql php 单引号或撇号
- azure - Azure 流分析查询
- git - GitLab如何将合并标签添加到分支
- c++ - 通用 lambda 的熟悉模板语法
- google-apps-script - 如何检查文件是属于我的云端硬盘还是团队云端硬盘
- mysql - 从mysql获取结果后无法写入文件