Pinia Composition API访问state时出现undefined错误的问题
问题
我定义了如下Pinia store:
export const useNotesStore = defineStore('notes', () => { const initialData = computed(() => ({ banner: "", title: "", group: "", newGroup: "", content: "", favorite: false, })) const newNote = ref({ ...initialData.value }); const parsed = JSON.parse(localStorage.getItem("notes")) || []; const notes = ref([...parsed]); const addNote = (payload) => {}; return { initialData, newNote, notes, addNote, }; });
并在页面中按如下方式导入并使用该store:
import { useNotesStore } from '@/stores/notes'; const notesStore = useNotesStore(); const handleSelectBanner = (value) => { // 打印时能看到对应值 console.log(notesStore.newNote); // 此行代码抛出错误 notesStore.newNote.value.banner = value; }
打印notesStore.newNote的结果为:
Proxy(Object) {banner: '', title: '', group: '', newGroup: '', content: '', …}
但点击模板中的按钮触发该方法时,会抛出错误:
Uncaught TypeError: Cannot set properties of undefined (setting 'banner')
我知道访问state时通常需要使用.value,但为何此处会出现undefined?我是否遗漏了什么?
注:我正在学习Vue.js的Pinia用法。
解决方法
问题核心是Pinia的自动解包机制:
- 在Pinia的setup风格store中返回
ref时,Pinia会自动将其解包为原始值。也就是说,组件中notesStore.newNote直接指向的是ref包裹的对象,而非ref实例本身。 - 此时调用
notesStore.newNote.value,相当于访问普通对象的value属性——这个属性不存在,所以返回undefined,自然无法设置banner。
修正后的代码只需移除多余的.value:
const handleSelectBanner = (value) => { notesStore.newNote.banner = value; }
额外优化:initialData使用computed完全没必要,它是固定的初始配置,直接定义为普通对象即可:
// 替换原有的computed定义 const initialData = { banner: "", title: "", group: "", newGroup: "", content: "", favorite: false, }; const newNote = ref({ ...initialData });
内容的提问来源于stack exchange,提问作者Seven
相关产品推荐
相关产品推荐

