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

155
Visualizações
Mobx observer component doesn't get update after observable change

I have the following MobX class that maintain async operation:

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

class AsyncAction<T, P = void> {
  public isLoading = false;
  public error?: unknown;
  public response?: T;

  constructor(
    private asyncAction: (payload: P) => Promise<T>,
  ) {
    makeObservable(this, {
      error: observable,
      isLoading: observable,
      response: observable,
      setLoading: action,
      setError: action,
      setResponse: action,
    });
  }

setLoading(isLoading: boolean) {
    this.isLoading = isLoading;
  }

  setError(error: unknown) {
    this.error = error;
  }

  setResponse(response: T | undefined) {
    this.response = response;
  }

  async run(payload: P) {
    try {
      this.setLoading(true);
      const response = await this.asyncAction(payload);
      this.setResponse(response);
    } catch (error) {
      this.setError(error);
    } finally {
      this.setLoading(false);
    }
  }
}

export { AsyncAction };

I also have the following store that extends AsyncAction:

import api from '../api';
import { AsyncAction } from "./AsyncAction";

class StatusesStore extends AsyncAction<Record<string, Status>> {
  constructor() {
    super(async () => {
      const { statusesMap } = await api.fetchStatusesMap();
      return statusesMap;
    });

    makeObservable(this, {
      setStatus: action,
    });
  }

  public setStatus(name: string, status: Status) {
    if (this.response) {
      this.response[name] = status;
    }
  }
}

When I trigger from my component rootStore.statusesStore.setStatus('name', 'DONE'), the component doesn't get updated.
When open devools, I see the following: enter image description here Instead of being wrapped with observable, the object keys are plain strings. This might be a reason why changing the status string triggers nothing.
How can I fix that? What am I missing?

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

0

Since async processes are resolved in the next tick of the event loop, mobx can't track the changes after the tick. One of the solutions is to use runInAction function after every await keyword.

Like this:

  import {runInAction} from 'mobx'
  async run(payload: P) {
    try {
      this.setLoading(true);// this is okay
      const response = await this.asyncAction(payload);
      // everything after "await" must be wrapped
      runInAction(()=>{
           this.setResponse(response);
      })

    } catch (error) {
      this.setError(error); // wrap in runInAction 
    } finally {
      this.setLoading(false); // wrap in runInAction 
    }
  }

There are also a few other alternatives how you can deal with promises in combination with Mobx. For me, runInAction is the most straightforward way.

For other examples check out official documentation: Asynchronous actions

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