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

Next.js 13中cache: 'no-store'不生效问题求助

Next.js Server Component 实现每次加载都请求API的解决方案

你在Next.js的Server Component中想要每次加载页面都向API请求数据,已经配置了fetch的cache: 'no-store',也设置了revalidate: 0,还导入了server-only,但只有首次加载会发起请求,后续都用缓存,可按以下步骤排查解决:

1. 确认Next.js路由模式

确保你的代码是在App Router(Next.js 13及以上版本)中运行,Pages Router的缓存逻辑和Server Component不兼容,你的写法是App Router的正确形式,但如果误用到Pages Router就会失效。

2. 强化fetch的缓存禁用配置

虽然你已经加了cache: 'no-store',但可以同时添加next: { revalidate: 0 }到fetch选项,双重确保禁用缓存:

async function getPosts() {
    const res = await fetch('http://localhost:4000/posts', {
        cache: 'no-store',
        next: { revalidate: 0 }
    })
    return res.json()
}

3. 排查开发环境的缓存干扰

开发模式下Next.js有默认缓存优化,你可以:

  • 重启开发服务器(npm run dev重新启动)
  • 打开浏览器开发者工具,勾选「Disable cache」选项后再刷新页面测试

4. 检查生产环境的静态导出设置

如果是生产环境,确认next.config.js里没有设置output: 'export'这类静态导出配置,这会强制页面静态生成,覆盖revalidate: 0的动态渲染(SSR)设置。

5. 排查后端API的缓存头

有时候问题出在API端,后端可能返回了Cache-Control缓存头(比如max-age=3600),导致浏览器或CDN缓存了响应。可以在浏览器开发者工具的「Network」标签中查看请求的响应头,若存在缓存指令,需要在API端修改为no-cache或no-store。

修改后的完整代码

import 'server-only';

async function getPosts() {
    const res = await fetch('http://localhost:4000/posts', {
        cache: 'no-store',
        next: { revalidate: 0 }
    })
    // 可选:添加错误处理,避免请求失败时页面崩溃
    if (!res.ok) {
        throw new Error('获取文章列表失败');
    }
    return res.json()
}

export const revalidate = 0;

export default async function ServerPage() {
    const posts = await getPosts()

    return (
        <div>
            <h2>Server Props...</h2>

            <ul>
                {posts?.map(({ id, title, body }) => (
                    <li key={id.toString()}>
                        <strong>{title}-{id}</strong>
                        <p>{body}</p>
                    </li>
                ))}
            </ul>
            
        </div>
    )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 16:20:21