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

Vue Fetch本地与Netlify部署表现不一致 Vuex数组重复累加异常

Vuex 数据重复累加问题修复方案

问题根因

  • 状态污染:Netlify 静态构建阶段会复用 Vuex 实例,加上你拉取数据时直接用push追加、没有前置清空逻辑,构建时预取的 state 会被序列化注入到客户端,跨页面跳转时 fetch 钩子重复触发就会持续累加数据;本地 dev 环境每次热更新/请求都会新建 Store 实例,因此无法复现该问题。
  • 状态字段缺失:代码中向geographicPatches、secretPatches数组提交数据,但 state 初始化时没有声明这两个字段,严格模式下会直接抛错阻断逻辑执行,这也是线上控制台无日志输出的核心原因——脚本执行被报错打断,后续的console.log和业务逻辑都不会运行。
  • 判断逻辑不可靠:直接读取组件映射的rawPatches做长度判断,在客户端 hydration 阶段可能拿到未完成响应式绑定的临时状态,导致length <=0的判断误判,重复触发拉取逻辑。

修复代码

1. 修正 Vuex Store 配置(index.js)

首先补全所有state字段,拉取数据前先清空对应数组,避免重复追加;减少循环内的commit次数,提升性能:

export const state = () => ({
  rawPatches: [],
  geographicPatches: [],
  secretPatches: [],
  // 加拉取锁,避免并发重复请求
  isPatchesLoading: false
});

export const mutations = {
  // 重置补丁数组的方法
  resetPatches(state) {
    state.rawPatches = [];
    state.geographicPatches = [];
    state.secretPatches = [];
  },
  setPatches(state, { raw, geographic, secret }) {
    state.rawPatches = raw;
    state.geographicPatches = geographic;
    state.secretPatches = secret;
  },
  setLoading(state, status) {
    state.isPatchesLoading = status;
  }
}

export const actions = {
  async readPatches({ commit, state }) {
    // 正在拉取时直接返回,避免重复请求
    if (state.isPatchesLoading) return;
    // 拉取前先重置数组+开加载锁
    commit('resetPatches');
    commit('setLoading', true);
    try {
      const patches = await this.$content('patches').fetch();
      const geographic = [];
      const secret = [];
      // 先在内存里分类,一次性提交到state
      patches.forEach((patch) => {
        if (patch.categories) {
          const categoryStr = JSON.stringify(patch.categories);
          if (categoryStr.includes('orbit') || categoryStr.includes('point')) {
            geographic.push(patch);
          }
        }
        if (patch.isSecret) {
          secret.push(patch);
        }
      });
      commit('setPatches', {
        raw: patches,
        geographic,
        secret
      });
    } finally {
      commit('setLoading', false);
    }
  },
}

2. 修正 Header 组件 fetch 逻辑

直接从store拿最新状态判断,避免依赖组件映射的延迟值:

async fetch() {
  try {
    // 直接从store取最新状态,加锁判断避免重复拉取
    if (this.$store.state.rawPatches.length <= 0 && !this.$store.state.isPatchesLoading) {
      await this.$store.dispatch('readPatches');
    }
    this.readPersonalPatches();
  } catch (error) {
    console.log(error);
  }
},

额外验证点

部署前可以本地跑npm run generate后启动静态服务预览,和Netlify的运行环境一致,提前复现和验证问题,不用每次推代码到线上调试。


内容的提问来源于stack exchange,提问作者Katie N.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 21:30:46