Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading