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

Next.js中useSWR配合axios请求时返回data为undefined

问题根因

subjects 始终为undefined的核心原因是自定义的fetchSubjects fetcher函数没有返回接口响应数据:
函数内虽然通过axios发起了请求、也在.then()回调中拿到了res.data,但没有将该值作为函数返回值返回,async函数在没有显式return值的情况下默认返回undefined,SWR拿不到fetcher的执行结果,对应解构出的data字段(也就是重命名后的subjects)自然始终为undefined。

修复方案

只需要修改fetcher函数,显式返回请求结果即可,提供两种可直接替换的写法:

  • 写法1:保留原有Promise链写法,补充return
const fetchSubjects = async url => {
    console.log("url = " + url)
    // 新增return,将请求最终结果返回给SWR
    return await axios
        .get(url)
        .then(res => res.data)
        .catch(error => {
            if (error.response.status !== 409) throw error
            // 注意:如果接口返回409状态码属于业务正常场景,这里需要补充返回对应约定值,否则该场景下subjects仍为undefined
        })
}
  • 写法2:更易读的try/catch写法
const fetchSubjects = async url => {
    console.log("url = " + url)
    try {
        const res = await axios.get(url)
        return res.data
    } catch (error) {
        // 可选加可选链避免error.response不存在时报错
        if (error.response?.status !== 409) throw error
        // 409状态码场景按需返回对应业务值
    }
}

额外可选优化:当前useSubjects Hook从useSWR中解构了mutate方法但没有对外返回,如果后续需要手动触发数据刷新,可以把mutate加到返回值中:

export const useSubjects = (id = -1) => {
    const { data: subjects, error, mutate } = useSWR(
        id > 0 ? `api/get-subject-branch/${id}` : 'api/get-subject-branches',
        fetchSubjects,
    )

    return {
        subjects,
        error,
        mutate
    }
}

修改完成后,SWR即可正常接收到接口返回的学科数据,subjects变量不会再持续为undefined。


内容的提问来源于stack exchange,提问作者Joy Ram Sen Gupta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 14:24:26