Mobx Class 无法读取未定义的 属性 'loading'

Mobx Class Cannot read property 'loading' of undefined

使用 create-react-app 创建了 react-app

所以我将 mobx 与 React 结合使用并创建了以下 class:

import { action, decorate, observable } from "mobx";

class AuthStore {
  loading = false;

  login() {
    console.log(this.loading);
  }
}

decorate(AuthStore, {
  loading: observable,
  login: action
});

export default AuthStore;

它说加载是未定义的,但我不知道为什么...

错误不是说 loading 未定义,而是说 this 是。

this 的值取决于调用 login 的上下文,而不是声明它的位置。我没有看到 login 在 class 中被调用,这意味着它不会引用 class 实例。

最简单的解决方案是将函数转换为使用词法作用域的箭头语法(它将有 this 作为对 class 的引用)。

login = () => {
  console.log(this.loading);
}

另一种不太简洁的解决方案是手动将 this 绑定到构造函数中的函数。

class AuthStore {
  constructor() {
    this.login = this.login.bind(this)
  }

  loading = false;

  login() {
    console.log(this.loading);
  }
}

效果一样