Vue3结合Pinia开发时模板调用Actions报funcName不是函数如何解决
Pinia模板调用Action报
is not a function问题排查 这属于操作失误导致的问题,并非Vue3或Pinia的预期行为,Pinia官方本身支持在模板内直接调用store实例上挂载的action方法。
常见出错原因及修复方案如下:
- 解构store时错误处理了action
Pinia的state需要用storeToRefs包裹才能保持解构后的响应式,但action本身是普通方法,不需要做响应式转换。如果你用toRefs处理全量store,或者用storeToRefs处理action,都会导致方法被转成Ref对象,调用时就会抛出不是函数的报错。
错误写法示例:
<script setup> import { useUserStore } from '@/stores/user' import { toRefs } from 'vue' const userStore = useUserStore() // 错误1:toRefs处理全量store,action被转为ref const { login, userInfo } = toRefs(userStore) // 错误2:用storeToRefs处理action const { login } = storeToRefs(userStore) </script>
正确写法:
<script setup> import { useUserStore } from '@/stores/user' import { storeToRefs } from 'pinia' const userStore = useUserStore() // state用storeToRefs处理保持响应式 const { userInfo } = storeToRefs(userStore) // action直接从store实例解构,不要转ref const { login } = userStore </script>
如果模板里直接通过store实例调用action,不需要解构,直接返回完整的store实例即可:
<script setup> import { useUserStore } from '@/stores/user' // 直接返回store,模板内可直接调用userStore.login const userStore = useUserStore() </script> <template> <button @click="userStore.login(loginForm)">登录</button> </template>
- store定义错误
检查你定义store时,对应的方法是否写在了actions配置项内,不要误写到state或getters配置中:
// stores/user.js 正确示例 import { defineStore } from 'pinia' export const useUserStore = defineStore('user', { state: () => ({ userInfo: null }), actions: { // action必须定义在此处 async login(form) { const res = await fetch('/api/login', { body: form }) this.userInfo = await res.json() } } })
版本兼容问题
如果你使用的是<script setup>语法糖,需要保证Pinia版本在2.0.0稳定版以上,同时Vue3版本不低于3.2.0,旧版本对setup语法糖的适配存在已知bug会导致该问题。对store做了额外的响应式转换
不要用reactive()、toRaw()等方法处理store实例后再返回给setup,会破坏store本身的内部结构导致方法丢失。
内容的提问来源于stack exchange,提问作者syldman
相关产品推荐
相关产品推荐

