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

Next.js中使用useSWR时data始终为undefined的问题求助

问题排查与解决

你的代码核心问题出在fetcher函数上——它没有返回异步请求的Promise,导致useSWR无法获取到API返回的数据,始终处于加载状态。

修正后的代码

修复fetcher函数

在fetch调用前加上return,让函数返回Promise对象:

import useSWR from "swr";

const apiUrl = process.env.NEXT_PUBLIC_API_URL;

// 修复:添加return返回Promise
const fetcher = (url) => {
  return fetch(url).then((res) => res.json());
};

// 或者用更简洁的箭头函数写法
// const fetcher = (url) => fetch(url).then(res => res.json());

export default function useSocialMedia() {
  const url = apiUrl + "/socialMedia";
  const { data, error } = useSWR(url, fetcher);
  console.log("data : ", data);

  return {
    socialMedia: data,
    loading: !error && !data,
    error: error,
  };
}

额外检查项

  • 确认NEXT_PUBLIC_API_URL环境变量已正确配置,拼接后的完整URL(比如apiUrl + "/socialMedia")能在浏览器中正常访问,返回合法的JSON数据。
  • 检查API是否存在跨域(CORS)问题,若存在需在后端配置允许当前域名的跨域请求。
  • 可在fetcher中添加响应状态校验,提前捕获请求错误:
    const fetcher = (url) => {
      return fetch(url)
        .then((res) => {
          if (!res.ok) throw new Error('请求失败');
          return res.json();
        });
    };
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 23:15:49