You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vuex模块嵌套时state共享问题:用函数返回state替代对象字面量

Hey there! I’ve dealt with this exact Vuex gotcha before, so I totally get how frustrating it is when your nested modules end up sharing the same state unexpectedly. Let me break down what’s happening and how to fix it:

The Problem Scenario

You’re reusing the same Vuex module by nesting it inside multiple other modules, but you defined your state as a plain object literal like this:

// Your original module definition
const myModule = {
  state: {
    count: 0,
    message: "Hello"
  },
  // mutations, actions, getters...
}

The issue? Every instance of this nested module ends up sharing the exact same state—when you update count in one nested module, it updates everywhere else too.

Why This Happens

In JavaScript, objects are reference types. When you assign a plain object as the state property, every time you import and use this module, it’s pointing to the same underlying object in memory. There’s no new instance created for each nested module, so they all share that single state reference.

The Fix: Return State From a Function

Instead of defining state as an object literal, define it as a function that returns a new object every time the module is initialized. This ensures each nested module gets its own independent state instance:

// Fixed module definition
const myModule = {
  state() {
    return {
      count: 0,
      message: "Hello"
    }
  },
  // mutations, actions, getters stay the same...
}

Now whenever you nest this module inside others, each one will call the state() function and get a fresh, separate state object—no more shared state surprises!

内容的提问来源于stack exchange,提问作者Andrew Kim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:55:42