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

时间:2019-12-08 22:50:51

标签: typescript mobx mobx-react

我正在用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:无法读取未定义的属性“ count”

指向

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

1 个答案:

答案 0 :(得分:1)

this未附加到该函数,而是由调用上下文引入。您可以使用@action.bound来解决它:

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

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

更多

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