如何在Nuxt组合式函数中使用runtimeConfig?
解决方案
问题根源
你的代码在模块顶层直接调用了useRuntimeConfig(),此时Nuxt实例尚未初始化,因此触发了nuxt instance unavailable错误。Nuxt的可组合函数(如useRuntimeConfig)必须在Nuxt上下文激活时调用——也就是在组件、Pinia action或其他可组合函数的内部逻辑中调用。
修正后的composables/apiFetch.ts
将useApiFetch改为可组合函数,在函数内部获取运行时配置并发起请求:
import { $fetch, type FetchOptions } from 'ohmyfetch' // 支持泛型,方便接口返回值的类型推导 export const useApiFetch = <T = unknown>(url: string, options: FetchOptions = {}) => { // 在函数内部调用useRuntimeConfig,确保处于Nuxt上下文环境 const runtimeConfig = useRuntimeConfig() return $fetch<T>(url, { baseURL: runtimeConfig.apiUrl, ...options }) }
Pinia中的用法(无需修改原有调用逻辑)
actions: { async doSomething(payload: SomeNicePayload): Promise<void> { // 直接调用useApiFetch即可,此时已处于激活的Nuxt上下文 const response = await useApiFetch('/something', { method: 'POST', body: payload }) } }
补充:RuntimeConfig配置
确保在nuxt.config.ts中正确关联.env的API地址:
export default defineNuxtConfig({ runtimeConfig: { // 仅服务器端可访问的变量(从.env读取) apiUrl: process.env.API_URL, public: { // 如果前端需要暴露API地址,可在此配置 // apiUrl: process.env.NUXT_PUBLIC_API_URL } } })
对应的.env文件:
API_URL=https://your-laravel-api-domain.com/api
可选写法(复用fetch实例)
如果需要统一添加全局请求配置(如请求头),可以改为返回复用的fetch实例:
import { $fetch } from 'ohmyfetch' export const useApiFetch = () => { const runtimeConfig = useRuntimeConfig() return $fetch.create({ baseURL: runtimeConfig.apiUrl, // 全局请求配置示例 headers: { 'Accept': 'application/json' } }) }
Pinia中用法:
actions: { async doSomething(payload: SomeNicePayload): Promise<void> { const apiFetch = useApiFetch() const response = await apiFetch('/something', { method: 'POST', body: payload }) } }
内容的提问来源于stack exchange,提问作者Yura
相关产品推荐
相关产品推荐

