【问题标题】:undefined this.setState inside 'then' blockundefined this.setState inside 'then' 块
【发布时间】:2021-02-05 18:16:57
【问题描述】:

我有以下功能,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 });
      });
    });
  }

但是我得到以下错误

Uncaught (in promise) TypeError: Cannot read property 'setState' of 未定义

对于这行代码this.setState({ disabledButton: true })

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

【问题讨论】:

    标签: reactjs


    【解决方案1】:

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

    变化:

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

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

    【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      • 2021-11-15
      • 2017-07-22
      • 1970-01-01
      • 2023-03-26
      相关资源
      最近更新 更多