0

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 | }

1 Answers1

0

this is not attached to the function and is being brought in by the calling context. You can fix it by using @action.bound:

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

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

More

Mobx docs : https://mobx.js.org/refguide/action.html

basarat
  • 261,912
  • 58
  • 460
  • 511