I'm facing a perplexing issue in my Vue application that has left me puzzled. The error message I'm encountering when trying to update a local version of a state element reads as follows:
Error: [vuex] Do not mutate vuex store state outside mutation handlers.
Below is a snippet of the code causing this issue:
import { mapGetters } from 'vuex'
export default {
name: 'sampleComponent',
data() {
return {
userModel: null
}
},
mounted() {
this.userModel = this.user
},
computed: {
...mapGetters(['getApplicationUsers']),
user() {
return JSON.parse(JSON.stringify(this.getApplicationUsers[0]))
}
},
methods: {
addUserRole() {
if (!this.userModel.userRoles.includes("newRole")) {
this.userModel.userRoles.push("newRole")
}
}
removeUserRole() {
let index = this.userModel.userRoles.indexOf("newRole");
if (index > -1) {
this.userModel.userRoles.splice(index, 1)
}
}
}
Whenever the removeUserRole function is invoked, the mutation error occurs. Adding roles with addUserRole works smoothly, but removing a role triggers the error message.
Could someone shed some light on this behavior for me? Shouldn't userModel
be independent from the state and mutable after being deep copied?