简体   繁体   中英

React Native mobx: Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed

I'm using mobx as state management for my react-native app, I'm modifying a simple array of ids like this:

let copyy = userStore.unreadChatIds;
copyy.push(e.message.chat_id);
userStore.setUnreadChatIds(copyy);

However I'm getting this mobx warning, I don't know why I'm getting it since I'm using makeAutoObservable in my mobx store

[MobX] Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: UserStore@1.unreadChatIds

My store

export class UserStore
{
    constructor()
    {
        makeAutoObservable(this);
        
unreadChatIds=[];

setUnreadChatIds(payload)
    {
        this.unreadChatIds = payload;
    }
}

Why am I getting this error and how can I solve it? afaik if using makeAutoObservable and use my setter method as action I'm not changing mobx state directly.

This warning occurs as you are modifying the userStore.unreadChatIds directly.

To resolve this, you should modifying the value via action

userStore.addChatId(e.message.chat_id);

Store

export class UserStore
{
    constructor()
    {
        makeAutoObservable(this, {
        unreadChatIds: observable,
        setUnreadChatIds: action,
        addChatId: action,
    });
        
unreadChatIds=[];

setUnreadChatIds(payload)
    {
        this.unreadChatIds = payload;
    }

addChatId(id)
 {
   this.unreadChatIds.push(id);
 }
}
 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM