Home > database >  React Native change state leads to mobx-state-tree exception
React Native change state leads to mobx-state-tree exception

Time:09-30

I have a problem with changing the value in my state. I have

state = {
    ......,
    tags: []
}

and these tags are filled like:

tags: this.props.userStore.details.tags

tags are a list of dictionaries:

tags = [{'name': tag1, 'userSelect': true}, {'name': tag2, 'userSelect': false}]

I display them all in the checkbox:

renderTagCheckbox() {
    return this.state.tags.map((item, key) => {
      return(
        <TouchableOpacity key={key} style={{flexDirection: "row", marginTop: 5, justifyContent: "center"}}>
          <CheckBox
            isChecked={item.userSelect}
            onClick={() => this.changeCheckboxValue(item)}
          />
          <Text>{item.name}</Text>
        </TouchableOpacity>
      )
    })
  }

in my changCheckboxValue() I have:

  changeCheckboxValue(item) {
    //this.refersSubscriptions.forEach(s => s.remove())
    let currentTags = this.state.tags
    currentTags.forEach(tag => {
      if (tag===item) {
        tag.userSelect = !tag.userSelect
      }
    })
  }

and this way I was thinking I could setState with currentTags where the value will be change, but I get an error:

[mobx-state-tree]Cannot modify 'tags@/userStore/details/tags/0', the object is protected and can only be modified by using an action.

Could somebody give me any tips on what am I doing wrong?

CodePudding user response:

From mobx-state-tree document:

By default, nodes can only be modified by one of their actions, or by actions higher up in the tree.

You put your tags in a global state which is an immutable object. so avoid changing your global state via inline codes in your component.

you can define propper actions and dispatch them for those changes.

for more information about the actions in mobx-state-tree look at the documentation.

  • Related