I'm writing a simple count store with MobX and TypeScript because I had some issues with JavaScript. This is the full code:
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
and decrement
are imported within a component and executed when clicking buttons.
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;
The problem is, when clicking, I receive this error:
TypeError: Cannot read property 'count' of undefined
pointing to
16 | @action
17 | increment() {
> 18 | this.count += 1;
19 | }