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

使用Pinia Options API设置状态时调用Action报错求助

问题分析与解决方案

错误原因

你在Pinia Store的actions里用了箭头函数定义getNavbarItems,箭头函数不会创建自己的this上下文,它的this继承自外层作用域,这里根本不是Pinia的store实例,所以执行this.navbarItems = data时,this是undefined,自然会抛出“无法设置undefined的属性”的错误。

修复方案

把getNavbarItems的箭头函数改成普通函数,Pinia会自动把this绑定到当前store实例上,就能正常访问并修改state里的navbarItems了。

修正后的代码:

import { defineStore } from "pinia";
import AxiosBeerOffice from "@/services/axiosBeerOffice";

const uri = {
  getNavbarItems: "/navbarItems",
};

export const useNavbarStore = defineStore({
  id: "navbar",
  state: () => ({
    navbarItems: [],
  }),
  actions: {
    // 替换为普通函数
    async getNavbarItems() {
      const response = await AxiosBeerOffice.get(uri.getNavbarItems, true);
      const { data } = response;
      this.navbarItems = data;
    },
  },
});

内容的提问来源于stack exchange,提问作者Ivan Parra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 10:12:13