nextjs
runtime_error
ai_generated
true
错误:不变量:headers() 期望有 requestAsyncStorage,但当前不可用。
Error: Invariant: headers() expects to have requestAsyncStorage, but none is available.
ID: nextjs/invariant-requestAsyncStorage-not-available
80%修复率
86%置信度
1证据数
2024-07-01首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| [email protected] | active | — | — | — |
| [email protected] | active | — | — | — |
| [email protected] | active | — | — | — |
根因分析
headers() 函数在有效的请求上下文之外被调用,例如在同步函数、实用程序文件或在没有请求的构建期间运行的组件中。
English
The headers() function is called outside of a valid request context, such as in a synchronous function, a utility file, or a component that runs during build time without a request.
官方文档
https://nextjs.org/docs/messages/invariant-headers-requestAsyncStorage解决方案
-
将 headers() 调用移入可用的请求上下文的异步服务器组件或 API 路由中。
-
如果在实用程序函数中需要标头,请从服务器组件将它们作为参数传递。
-
如果错误发生在中间件中,请确保 headers() 在中间件函数的顶层调用,而不是在嵌套的回调或条件语句中。
无效尝试
常见但无效的做法:
-
90% 失败
headers() is a server-only function; it cannot be called in client components even in useEffect.
-
85% 失败
The function will still throw an invariant error, and the catch block will not provide valid header data.
-
80% 失败
These functions run at build time without a request context, so headers() is not available.