class 主体中声明的变量在 TypeScript 和 MobX 的函数中未定义

Variable declared in class body is undefined within a function in TypeScript and MobX

我正在使用 MobX 和 TypeScript 编写一个简单的计数存储,因为我在使用 JavaScript 时遇到了一些问题。这是完整的代码:

import { observable, autorun, computed, action } from "mobx";

class CountStore {
  @observable
  count: number = 0;

  constructor() {
    autorun(() => console.log("Count: ", this.count));
  }

  @computed
  get getCount() {
    return this.count;
  }

  @action
  increment() {
    this.count += 1;
  }

  @action
  decrement() {
    this.count -= 1;
  }
}

export default new CountStore();

incrementdecrement 在组件中导入并在单击按钮时执行。

import React from "react";
import { observer } from "mobx-react";
import { Button } from "antd";
import CountStore from "./store/CountStore";
import "antd/dist/antd.css";

const App: React.FC = observer(() => {
  return (
    <>
      <Button type="primary" onClick={CountStore.increment}>
        +
      </Button>
      {CountStore.getCount}
      <Button type="primary" onClick={CountStore.decrement}>
        -
      </Button>
    </>
  );
});

export default App;

问题是,点击时,我收到此错误:

TypeError: Cannot read property 'count' of undefined

指向

  16 | @action
  17 | increment() {
> 18 |   this.count += 1;
  19 | }

this 未附加到函数,由调用上下文引入。您可以使用 @action.bound 修复它:

  @action.bound
  increment() {
    this.count += 1;
  }

  @action.bound
  decrement() {
    this.count -= 1;
  }

更多

Mobx 文档:https://mobx.js.org/refguide/action.html