Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

80
Visualizações
Cannot read properties of undefined - javascript class

I wanted to try mobx for react state management, however, I can't get this to work. I have this simple store for storing just a number called counter. You can increment/decrement it, and increse it by x. I have this file store.js for storing the state:

import { action, makeObservable, observable } from "mobx";


class CounterStore {
    counter = 0;

    constructor() {
        makeObservable(this, {
            counter: observable,
            increment: action,
            decrement: action,
            increase: action
        });
      
    }

    increment() {
        this.counter++;
    }

    decrement() {
        this.counter--;
    }

    increase(value) {
        this.counter = this.counter + value;
    }
}

const store = new CounterStore();

export default store;

And then I have this component named Counter inside Counter.js, which executes the methods like increment and decrement for the store

import { useRef } from "react";
import classes from './Counter.module.css'
import store from "../store";

function Counter() {

    const numberInput = useRef();

    const increaseHandler = (event) => {
        event.preventDefault(); 
        if (numberInput.current.value === ''){
            return;
        }
        store.increase(parseInt(numberInput.current.value))
    };
    return (
        <div>
            <div className={classes.counter}>{store.counter}</div>
            <div className={classes.row}>
                <button className={classes.btn} onClick={store.increment}>Increment</button>
                <button className={classes.btn} onClick={store.decrement}>Decrement</button>
            </div>
            <form className={classes.row} onSubmit={increaseHandler}>
                <button className={classes.btn}>Increase by x</button>
                <input className={classes.input} required="true " type="number" ref={numberInput} />
            </form>

        </div>
    );
}

export default Counter;

But when i press the button, I always get

Uncaught TypeError: Cannot read properties of undefined (reading 'counter') at increment

How can the counter possibly be undefined? I already export the instantiated store.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your function is losing context (this), you need to read about it to understand how it works. You destructured this function from the store and it is not bound to it anymore.

The most common way is to define all actions as arrow functions, like that:

    // Use arrow function to define methods
    increment = () => {
        this.counter++;
    }

    decrement = () => {
        this.counter--;
    }

    increase = (value) => {
        this.counter = this.counter + value;
    }

That way you don't need to worry about the context, it will be automatically bound to the current class.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda