javascriptreactjsmobxmobx-reactmobx-react-lite

mobx-react-lite: Cannot read properties of undefined


I have a simple component that just adds value in screen, but I'm receiving an error: Uncaught TypeError: Cannot read properties of undefined (reading 'value') at increment (initialState.js:11:7).

App.js:

return (
    <IncrementButton store={Store} />
);

IncrementButton.js:

import {observer} from 'mobx-react-lite';
import React from 'react';

export const IncrementButton = observer(({store}) => {
  return (
    <div>
      <button onClick={store.rebate.increment}>Increase</button>
      <h1>{store.rebate.value}</h1>
    </div>
  );
});

rootStore.js:

import {makeAutoObservable} from 'mobx';
import {initialState} from './initialState';

class RootStore {
  states = initialState;

  constructor() {
    makeAutoObservable(this);
  }
  increaseNumber = () => {
    this.states.rebate.increment();
  };
}

const Store = new RootStore();
export default Store.states;

initialState.js:

export const initialState = {
  rebate: {
    id: 1,
    name: 'Example',
    value: 3000,
    increment() {
      this.value = this.value++;
    },
  },
};

I'm also up to new tips since I'm starting with mobx-react-lite and only mobx-react-lite. It seems really difficult to find documentation about only mobx-react-lite. Thank you a lot!!


Solution

  • this is undefined inside your initialState's "method".

    Remove increment from initialState and write increaseNumber as

    increaseNumber = () => {
      this.states.rebate.value += 1;
    }