这在 Babel 编译的方法中是未定义的

this is undefined in Babel-compiled methods

我正在尝试使用 React 0.13 和 ES6 语法编写一个小型网络应用程序。我正在使用 webpack 和 babel-loader 来编译:

loaders: [
  { test: /\.js/, exclude: /node_modules/, loader: "babel-loader"}
]

我在使用方法内部的 this 变量时遇到问题,在我的代码中的多个位置出现 "this is undefined"。例如:

export class PanelEditor extends React.Component {
  ...
  update (){
    if (!this.isMounted())
      return;

    this.setState(this.getStateFromStore());
  }
  ...
}

在这种情况下,this 变量永远不应未定义。但是,我发现问题可能出在Babel重写代码的方式上:

update: {
  value: function update() {
    if (!this.isMounted()) {
      return;
    }
    this.setState(this.getStateFromStore());
  }
},

在我看来,this 变量指的是对象文字而不是 class .我该如何解决这个问题?

这实际上不是问题所在。就是 this 是未定义的,因为你没有绑定更新函数。

您可以在 constructor 或渲染中执行此操作。大多数人在渲染中这样做。

<div onClick={this.update.bind(this)} />

或者(我的偏好),一个保留 this.

的箭头函数
<div onClick={() => this.update()} />