Reputation: 1476
I am getting this warning in the console:
[vuex] state field "foo" was overridden by a module with the same name at "foo"
What does it mean and what can I have done wrong?
Upvotes: 10
Views: 6627
Reputation: 29092
This is a new warning added in Vuex 3.1.2.
https://github.com/vuejs/vuex/releases/tag/v3.1.2
It is logged when a property name within the state
conflicts with the name of a module, like so:
new Vuex.Store({
state: {
foo: 'bar'
},
modules: {
foo: {}
}
})
If you attempt to access state.foo
you might expect the value to be 'bar'
but it will actually refer to the state
of the foo
module.
You would fix this problem by removing the property from the state
object, or by renaming either the property or the module.
Here's a small example that logs the relevant warning and shows the resulting value of state.foo
:
const store = new Vuex.Store({
state: {
foo: 'bar'
},
modules: {
foo: { state: { flag: 2 } }
}
})
console.log(store.state.foo)
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vuex.js"></script>
Update:
This warning can also be logged if you create multiple stores using the same configuration object, e.g. during testing.
Here's an example:
const config = {
state: {},
modules: {
foo: {}
}
}
const store1 = new Vuex.Store(config)
const store2 = new Vuex.Store(config)
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vuex.js"></script>
The problem is that the configuration includes a root state
object. The first store adds the foo
module to that object. When the second store tries to do the same thing it finds that the property already exists and logs the error.
If the root state
object is empty, like it is in my example, then it could just be removed. However, assuming it isn't empty you'd fix this by changing it to a function instead:
const config = {
state () {
return {
/* state properties here */
}
},
modules: {
foo: {}
}
}
This works exactly the same way as the data
function for a component.
Upvotes: 22