首页 > 解决方案 > 我不能调用 this.function: TypeError: this.fetchData is not a function

问题描述

我打电话时收到此错误“TypeError:this.fetchData is not a function” this.fetchData();,我认为它this丢失了所以我尝试使用bind或箭头函数但它也不起作用,如何解决这个问题?

class ShowResults extends Component {
    getData() {
        return setTimeout(function() {
            this.fetchData();
          }, 2000); //tried to use bind but did not work--> .bind(this);
        }
      }

      async fetchData() {
        //code
      }
}

标签: javascripttypescript

解决方案


正如您所说,您需要.bind(this)因为您不在 setTimeout 函数内的同一范围内;您能否发送更多代码,您的括号数量有些奇怪。


推荐阅读