'then' 块内未定义 this.setState

时间:2021-02-05 18:16:57

标签: reactjs

我有以下函数,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 })

thisthen 块内无法访问?如何更新 then 块内的状态?

2 个答案:

答案 0 :(得分:2)

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

变化:

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

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

答案 1 :(得分:1)

ECMAScript 6 引入了箭头函数,就您而言,匿名函数在绑定之前无法访问“this”。他们没有自己的 this 绑定。相反,它就像一个普通变量一样在范围内查找。

首先需要在“.then”和“.catch”中添加箭头功能

 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 });
      });
    });
  }