使用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
相关产品推荐
相关产品推荐

