0

You can look at the issue via codesandbox

Codesandbox: https://codesandbox.io/s/great-frog-m2s7h

Context

I am trying to fetch some data and populate some variable and render the value in React, essentially following the documentation await/async + runInAction example: https://mobx.js.org/actions.html#asynchronous-actions

However, when the data is fetched, React actually does not re-render. However, if you edit the text in there(i.e. change hi to his or whatever, then you see the correct value appear.

Problem

What exactly am I doing wrong with the data fetching? Why isn't the observable value not being re-rendered correctly when its been assigned a value after some data has been fetched?

  • Does this answer your question? [Error: \[MobX\] Cannot apply 'observable' to 'Store@user': Field not found](https://stackoverflow.com/questions/67266810/error-mobx-cannot-apply-observable-to-storeuser-field-not-found) – Danila Jun 16 '21 at 14:16

2 Answers2

2

This is actually one of the limitations of Mobx.

From the docs:

make(Auto)Observable only supports properties that are already defined. Make sure your compiler configuration is correct, or as workaround, that a value is assigned to all properties before using make(Auto)Observable. Without correct configuration, fields that are declared but not initialized (like in class X { y; }) will not be picked up correctly.

Just initialize the title this.title=undefined and it will work.

Ivan V.
  • 7,593
  • 2
  • 36
  • 53
0

Its a simple mistake. MobX can not compare data of title to something that dosent exist. Stuff should have default value of some sort, even a null. hence in a constructor you need to define title default value like

constructor() {
    this.title = [],
    makeAutoObservable(this);
}

or, if you wish, even null

constructor() {
    this.title = null,
    makeAutoObservable(this);
}

Basiclaly, whenever you create some observable variable in a store - you need to define its default value in a constructor above makeAutoObservable.

Here, a forked project of yours with juswt this 1 line change to make it work https://codesandbox.io/s/suspicious-noether-fnhjw

Lith
  • 1,251
  • 6
  • 19