HTML 原文 · 完整 Markdown · 纯文本 · 分段目录 · ← 上一段 · 下一段 →

03-第 2 层:数据缓存 (Data Cache)

第 16 / 22 段:架构陷阱

Next.js 缓存机制全解析 · 发布 2026-02-20 · 更新 2026-11-11 · 标签:Next.js、缓存、前端架构、React

架构陷阱

⚠️ 非 fetch 请求不会自动缓存

// ❌ 这些不会被缓存
import axios from "axios";
import { prisma } from "@/lib/prisma";

// 1. axios
const res = await axios.get("https://api.example.com/posts");

// 2. Prisma
const posts = await prisma.post.findMany();

// 3. 其他 HTTP 库
const res = await got("https://api.example.com/posts");

✅ 解决方案:使用 use cache 指令(Next.js 16+)或 unstable_cache

在 Next.js 16+ 中,推荐使用 use cache 指令来缓存非 fetch 的数据获取:

import { prisma } from "@/lib/prisma";
import { cacheTag } from "next/cache";

// ✅ 使用 use cache 指令缓存数据库查询
export async function getPosts() {
  "use cache";
  cacheTag("posts");

  return await prisma.post.findMany();
}

// 使用
const posts = await getPosts();

如果你还在 Next.js 15 上,可以使用 unstable_cache: