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

Next.js中unstable_cache无法缓存数据的问题排查

解决unstable_cache在Edge Runtime服务器组件中不生效的问题

问题根源

你的代码存在两个关键问题导致缓存失效:

  1. 缓存Key未区分请求参数:缓存Key仅设置为['product'],但请求依赖country参数,不同国家的请求需要独立缓存条目,相同Key会导致缓存无法正确区分场景。
  2. 缓存实例被重复创建:每次调用fetchProductWithCache时,都会重新执行unstable_cache(...)(),相当于每次新建缓存实例而非复用,直接导致缓存机制失效。

修复代码

export const runtime = 'edge';
export const revalidate = 10;

// 全局定义缓存函数,确保实例稳定
const fetchProductWithCache = unstable_cache(
  async (country?: Country) => {
    console.log('fetch product from unstable_cache');
    return fetchProductWithDelay(country);
  },
  // 动态生成包含country的缓存Key,区分不同请求
  (country) => ['product', country],
  { revalidate: 10, tags: ['product'] }
);

export const generateStaticParams = async () => {
  const countries = await api.product.countries();
  console.log('[PRODUCT] generating static paths:', countries);
  return countries.map((country) => ({ country }));
};

export default async function Page({ params }: { params: Props }) {
  const { country } = params;
  console.log('[PRODUCT] generating static product:', country);
  const product: any = await fetchProductWithCache(country)
  const parityPrice = getDiscountedPrice(product.price, product.discount);

  if (!country || !product) {
    return <div />;
  }
  return (
    <>
      <div className="ml-14 lg:ml-24 -mb-40 lg:-mb-56">
        {/* 组件内容 */}
      </div>
    </>
  );
}

修复说明

  • 缓存函数全局化:将unstable_cache的调用移到函数外部,模块加载时就创建好缓存实例,每次调用fetchProductWithCache都是复用同一个实例,确保缓存能正常命中。
  • 动态生成缓存Key:用函数形式生成Key,把country参数包含进去,让不同国家的请求拥有独立缓存条目,避免混淆。
  • 简化参数校验:原代码中Object.keys(country).length === 0的判断可简化为!country,逻辑一致且更简洁。

额外提示

  • Edge Runtime下,unstable_cache的缓存依赖平台Edge缓存实现,需确保部署环境支持(如Vercel Edge Network)。
  • 若使用generateStaticParams生成静态路径,首次构建会预渲染所有国家的页面,后续请求直接命中静态缓存;非预渲染路径的动态请求才会触发unstable_cache逻辑。

内容的提问来源于stack exchange,提问作者Joey Yi Zhao

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 16:41:08