MobX requires you to wrap any function which updates an observable in an action, otherwise you’ll see this error:

However, action only affects the currently running function, not any functions which are scheduled by the current function. This means if your function has any asynchronous callback such as a setTimeout or .then() which update observables, applying the action decorator to the function won’t work. The following code will still throw an error:

This is because the async callback itself needs to be wrapped in an action. Here we’re calling setMedia, which is an action:

A simple way to do this without creating a new function is to use runInAction. This is a way to define an anonymous action, and immediately invoke it:

Hope this helped!

Software Developer 👩‍💻