vuex: state field “foo” was overridden by a module with the same name at “foo”

Total
4
Shares

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?


Solution

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:

_x000D_

_x000D_

const store = new Vuex.Store({_x000D_
  state: {_x000D_
    foo: 'bar'_x000D_
  },_x000D_
  modules: {_x000D_
    foo: { state: { flag: 2 } }_x000D_
  }_x000D_
})_x000D_
_x000D_
console.log(store.state.foo)

_x000D_

<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<script src="https://unpkg.com/[email protected]/dist/vuex.js"></script>

_x000D_

_x000D_

_x000D_

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:

_x000D_

_x000D_

const config = {_x000D_
  state: {},_x000D_
_x000D_
  modules: {_x000D_
    foo: {}_x000D_
  }_x000D_
}_x000D_
_x000D_
const store1 = new Vuex.Store(config)_x000D_
const store2 = new Vuex.Store(config)

_x000D_

<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<script src="https://unpkg.com/[email protected]/dist/vuex.js"></script>

_x000D_

_x000D_

_x000D_

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.

Leave a Reply

Your email address will not be published. Required fields are marked *