I get a warning 'changing observable values without using an action is not allowed.' How the action works? #2552
-
mobx warned me that I should change the variable by wrapping it in an action
import Axios from 'axios';
import { action, makeAutoObservable } from 'mobx';
export type PostStore = {
loadPosts: () => void;
posts: { id: number; title: string }[];
};
const exampleStore = (): PostStore => {
return makeAutoObservable<PostStore>(
{
posts: [],
async loadPosts() {
const { data } = await Axios.get('https://my-json-server.typicode.com/typicode/demo/posts');
const posts: [] = data;
action(() => {
this.posts = posts.map(x => x);
})();
},
},
{ loadPosts: action },
);
};
export { exampleStore }; if I wrap the whole function in an action then the warning appears again async loadPosts() {
action(async () => {
const { data } = await Axios.get(
'https://my-json-server.typicode.com/typicode/demo/posts',
);
const posts: [] = data;
this.posts = posts.map(x => x);
})();
}, why? how to wrap a function in an action, and safely update the variable without getting warnings? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
We do write docs for a reason.... |
Beta Was this translation helpful? Give feedback.
We do write docs for a reason....
https://mobx.js.org/actions.html#asynchronous-actions