错误:'use cache' 不允许在客户端组件中使用。请仅在服务端组件或服务端操作中使用 'use cache'。
Error: 'use cache' is not allowed in Client Components. Use 'use cache' only in Server Components or Server Actions.
ID: nextjs/use-cache-in-client-component
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Next.js 15.x | active | — | — | — |
| React 19.x | active | — | — | — |
根因分析
标记为 'use client' 的组件或函数包含了 'use cache' 指令,该指令是仅用于服务端组件的特性,用于缓存数据和计算。
English
A component or function marked with 'use client' contains a 'use cache' directive, which is a Server Component-only feature for caching data and computations.
官方文档
https://nextjs.org/docs/app/api-reference/directives/use-cache解决方案
-
将数据缓存逻辑移到服务端组件中,并将结果作为 props 传递给客户端组件。示例:// 服务端组件(无 'use client')export default async function Page() { 'use cache'; const data = await fetchData(); return <ClientComponent data={data} />; } -
如果需要在客户端进行缓存,请使用 React 内置的 cache 函数(来自 'react')而不是 'use cache'。示例:import { cache } from 'react'; const getData = cache(async () => { ... }); -
通过移除 'use client' 并将所有客户端逻辑重构到单独的客户端子组件或使用服务端操作,将整个组件转换为服务端组件。
无效尝试
常见但无效的做法:
-
70% 失败
The component likely uses client-side hooks (useState, useEffect, etc.) or event handlers that require 'use client'. Removing it will cause other errors.
-
90% 失败
The 'use cache' directive is not supported anywhere in the client component tree, including nested components that are still within a client boundary.
-
100% 失败
This is a build-time or runtime validation error that cannot be caught by try-catch. The framework actively prevents 'use cache' in client components.