'this' 未定义 - ReactJS

'this' is undefined - ReactJS

我正在构建一个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) 以将上下文绑定到我的函数,但没有任何改变。有什么想法吗?

箭头函数无处不在,因此上下文取自函数 handleMerging()。如果您像这样调用该函数,this 上下文将是未定义的(如果使用严格模式)或 window 对象。您将需要向该函数添加绑定,但仅当从对象(或者正如您从 React Component 所说的那样,但它需要 class 不是函数 - 简单组件 - 因为它将没有 this 上下文)。

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

或组件:

class C extends ReactComponent {

   constructor() {
      var handleMerging = handleMerging.bind(this);

      handleMerging().then(...);
   }
}

但是这需要从真实的对象上下文中调用,所以在方法内部调用,如果在外部调用 function/method 它没有任何意义,因为即使你使用 bind 也是未定义的。