我正在用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();
increment
和decrement
导入到组件中,并在单击按钮时执行。
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 | }
答案 0 :(得分:1)
this
未附加到该函数,而是由调用上下文引入。您可以使用@action.bound
来解决它:
@action.bound
increment() {
this.count += 1;
}
@action.bound
decrement() {
this.count -= 1;
}