Nuxt3中Pinia调用封装useFetch的Composable时出现实例访问错误
问题解决:Nuxt3中Pinia调用封装的useFetch Composable报错
错误原因
你在Composable的模块顶层直接调用了useRuntimeConfig(),模块加载阶段没有Nuxt实例上下文,当Pinia Store调用这个Composable时,顶层的useRuntimeConfig()会先执行,触发报错。
修复方案
把useRuntimeConfig()的调用移到useApiFetch函数内部,确保每次调用该函数时,都是在有Nuxt实例上下文的环境中执行这个Composable:
修改后的Composable代码:
import { UseFetchOptions } from "nuxt/app"; export function useApiFetch<T>(path: string, options: UseFetchOptions<T> = {}) { // 将useRuntimeConfig移到函数内部 const config = useRuntimeConfig(); return useFetch(config.public.BASE_API_URL + path, { ...options, }); }
Pinia Store中的调用代码无需修改,保持原样即可:
export const useAuthStore = defineStore("auth", () => { const user = ref<User | null>(null); const isLoggedIn = computed(() => !!user.value); async function logout() { await useApiFetch("/logout", { method: "POST" }); user.value = null; token.value = null; navigateTo("/auth"); } });
原理说明
Nuxt的Composable(比如useRuntimeConfig、useFetch)必须在Vue setup函数、Nuxt插件、钩子、中间件或者由这些上下文调用的函数内部执行。把useRuntimeConfig移到函数内部后,只有当useApiFetch被调用时才会执行它,此时处于Pinia的函数执行上下文(Pinia的defineStore是在Vue setup环境中运行的),就能正确获取到Nuxt实例。
内容的提问来源于stack exchange,提问作者juancho perez
相关产品推荐
相关产品推荐

