You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt3中useLazyFetch结合computed值返回空字符串问题排查

Nuxt3中useLazyFetch响应式参数丢失问题解决

问题描述

在Nuxt3中使用自定义useAPILazyFetch组合式函数时,遇到响应式参数丢失导致请求失败的问题:

自定义的useAPILazyFetch函数:

import { useLazyFetch } from 'nuxt/app'
import { useUserManagerStore } from '~/stores/userManagerStore'

type useFetchType = typeof useLazyFetch

export const useAPILazyFetch: useFetchType = (path, options = {}) => {
  const config = useRuntimeConfig()
  const userManagerStore = useUserManagerStore()
  options.baseURL = config.public.baseURL
  options.headers = [
    ['Authorization', 'Bearer ' + (userManagerStore.user?.access_token || '')]
  ]
  return useLazyFetch(path, options)
}

获取用户信息的调用:

const { data: userInfo, pending: pendingUser } = await useAPILazyFetch<IUser>(
  ApiEndpoints.GET_USER_BY_ID,
  { query: { contactId } }
             ^^^^^^^^^  - 这是来自props的ref
)

创建computed属性获取上级ID:

const computedHead1Id = computed(() => {
  return useUnProxy(userInfo)?.head1Id || ''
})

调用useLazyFetch获取上级信息时,computedHead1Id始终返回空字符串:

const {
  data: head1Info,
  pending: pendingHead1Info,
  error: head1InfoError
} = await useAPILazyFetch<IUser>(() => ApiEndpoints.GET_USER_BY_ID, {
  immediate: false,
  watch: [computedHead1Id],
  query: { contactId: computedHead1Id.value }
})

问题分析与解决

1. computed中错误调用组合式函数

computed计算属性内部不能调用use开头的组合式函数(如useUnProxy),这违反了Nuxt3组合式API的调用规则,会导致无法正确获取响应式值。同时,userInfo是ref类型,直接访问.value即可获取数据,无需useUnProxy。

修正后的computed属性:

const computedHead1Id = computed(() => {
  return userInfo.value?.head1Id || ''
})

2. query参数丢失响应式

直接赋值computedHead1Id.value只会拿到初始值,当computed值更新时,query不会自动同步。需要将query设置为函数形式,让useLazyFetch在每次触发请求时重新计算参数值。

修正后的上级信息请求:

const {
  data: head1Info,
  pending: pendingHead1Info,
  error: head1InfoError
} = await useAPILazyFetch<IUser>(ApiEndpoints.GET_USER_BY_ID, {
  immediate: false,
  watch: [computedHead1Id],
  query: () => ({ contactId: computedHead1Id.value })
})

3. 自定义函数中headers设置问题

原代码中直接将options.headers赋值为二维数组,会覆盖原有headers且不符合Fetch API规范。建议改为对象形式合并headers,保留可能存在的自定义headers:

修正后的useAPILazyFetch:

import { useLazyFetch } from 'nuxt/app'
import { useUserManagerStore } from '~/stores/userManagerStore'

type useFetchType = typeof useLazyFetch

export const useAPILazyFetch: useFetchType = (path, options = {}) => {
  const config = useRuntimeConfig()
  const userManagerStore = useUserManagerStore()
  
  options.baseURL = config.public.baseURL
  // 合并headers,避免覆盖原有配置
  options.headers = {
    ...options.headers,
    Authorization: `Bearer ${userManagerStore.user?.access_token || ''}`
  }
  
  return useLazyFetch(path, options)
}

内容的提问来源于stack exchange,提问作者Vitaliy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 03:10:29