javascript - JS React : error of this. x 不是函数,即使绑定(bind)了 this.x 函数

标签 javascript reactjs

每当安装应用程序组件时,我都会尝试进行更新以更新窗口状态。使用下面的代码,我收到 响应 tabs.query 的错误:TypeError: this.addTabs is not a function

我不明白为什么 this.addTabs 不被视为函数,因为该函数位于对 this.addTabs(tabs) 的引用之上,并且我认为它已正确绑定(bind)。

class App extends Component {
 constructor(props){
  super(props);
  this.state = {
     window: []
  };
  this.addTabs = this.addTabs.bind(this);
}

addTabs(tabs){
  this.setState({window:this.state.window.concat(tabs)});
};

componentDidMount(){
  chrome.tabs.query({active:true},function(tabs){
    this.addTabs(tabs);
});

我不想使用箭头功能。我查看了类似的问题,答案是在构造函数中绑定(bind)函数,我相信我做到了。任何帮助或指示将不胜感激!

最佳答案

您的问题在此 block 中:

componentDidMount(){
  chrome.tabs.query({active:true},function(tabs){
    this.addTabs(tabs);
  });
}

在回调中,上下文不同,因此 this 引用另一个上下文。

您有多种方法可以修复它。

1) 在回调之外将引用分配给 this 并使用该引用:

componentDidMount(){
  const that = this;
  chrome.tabs.query({active:true},function(tabs){
    that.addTabs(tabs);
  });
}

2)将当前的this绑定(bind)到回调:

componentDidMount(){
  chrome.tabs.query({active:true},(function(tabs){
    this.addTabs(tabs);
  }).bind(this));
}

3)使用箭头函数:

componentDidMount(){
  chrome.tabs.query({active:true}, (tabs) => {
    this.addTabs(tabs);
  });
}

关于javascript - JS React : error of this. x 不是函数,即使绑定(bind)了 this.x 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53905045/

相关文章:

css - 需要帮助设计 react-native-elements 输入组件

javascript - 验证 <paper-input> 值的变化而不是按键?

Javascript 和 Ajax - 填充对象的更好方法?

reactjs - 如何在 Next.js 中使用 webrtc-adapter npm 包

reactjs - 不理解以奇怪的对象类型作为参数的 TypeScript 函数签名

javascript - 如何从 URL 获取帖子的 ID

javascript - 正则表达式:获取特定子字符串前后的数字

javascript - sIFR:动态插入变音符号会导致麻烦

javascript - 如何使用 jQuery 提取单个句子?

javascript - 使用 Javascript 解码动画 WebP (React/NextJS)