首页 > 解决方案 > 'this' 未定义 - 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)以将上下文绑定到我的函数,但没有任何改变。有任何想法吗 ?

标签: javascriptreactjsthis

解决方案


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

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

或与组件:

class C extends ReactComponent {

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

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

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


推荐阅读