首页 > 解决方案 > 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块内的状态?

标签: reactjs

解决方案


是的,那是因为function's 可以设置自己的this上下文。您可以通过使用箭头函数轻松避免这种情况:

改变:

    actions.autoSubmit(exampleVarOne, exampleVarTwo).then(function (results) {

    actions.autoSubmit(exampleVarOne, exampleVarTwo).then((results) => {

推荐阅读