'this'是未定义的-ReactJS

时间:2019-08-24 08:20:17

标签: javascript reactjs this

我正在构建一个reactJS代码,以下代码。一直有效,直到我将this.requestCSVDownload()函数调用添加到我的then函数中为止。

async handleMerging(){
    console.log("merging launched...")

    this.launchMerging({
      userId: this.state.userId,
      noteId: this.state.noteId,
      type: this.state.type,
      dateUser: this.state.content
    });

    var intervalId = await setInterval(()=> {
      this.requestPercentage({
          userId: this.state.userId,
          noteId: this.state.noteId
      }).then(async result => {
        try{
          if(result.hasOwnProperty('Item') &&
              result['Item'].hasOwnProperty('mergingProgress') &&
              result['Item']['mergingProgress'].hasOwnProperty('N') &&
              result['Item']['mergingProgress']['N'] !== null){
            var percentage = parseInt(result['Item']['mergingProgress']['N']);
            this.setState({
              progressMerging: percentage
            });
            if(percentage === 100){
              var result = await this.requestCSVDownloadURL({
                          userId: this.state.userId,
                          noteId: this.state.noteId
                        });
              var csvFileURL = await Storage.vault.get(JSON.parse(result.Payload).body.replace("\"", "").replace("\"", ""));
              this.setState({
                csvFileURL
              });
              console.log(this.state.csvFileURL)
              clearInterval(intervalId)
              return;
            }
          }
        }
        catch(e){
          alert("An error occured...\nConvertion started, just wait a few minutes to see it appear..." + e);
        }
      });
    }, 1500);
  }

但是它告诉我this is undefined
我认为这属于我的then函数中
我尝试添加.bind(this)以将上下文绑定到我的函数,但是没有任何改变。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您到处都有箭头功能,因此上下文来自功能handleMerging()。如果像这样调用该函数,则this上下文将是未定义的(如果使用严格模式)或窗口对象。您将需要向该函数添加绑定,但是仅当从对象(或正如您从React Component所说的那样,但它必须是类非函数-简单组件)调用时才使用handleMerging.bind(this),因为它将没有{{1 }}上下文。)

this

或带有组件:

foo.x = function() {
   y.addEventListener('click', handleMerging.bind(this));
};

但是这需要从真实对象上下文中调用,因此在内部方法中,如果在函数/方法外部调用,则没有任何意义,因为即使使用bind,这也将是不确定的。