react
runtime_error
ai_generated
true
水合失败,因为初始 UI 与服务器渲染的内容不匹配。警告:期望服务器 HTML 在 <div> 中包含匹配的 <div>。
Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected server HTML to contain a matching <div> in <div>.
ID: react/hydration-error-undefined
80%修复率
85%置信度
1证据数
2023-03-20首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| [email protected] | active | — | — | — |
| [email protected] | active | — | — | — |
| [email protected] | active | — | — | — |
根因分析
服务器渲染的 HTML 结构与客户端首次渲染的结构不同,通常是由于浏览器特定的 API(如 localStorage、window)导致客户端和服务器输出不一致。
English
Server-rendered HTML structure differs from client's first render, often due to browser-specific APIs (e.g., localStorage, window) causing different output on client vs server.
官方文档
https://reactjs.org/docs/hydration.html解决方案
-
Use dynamic import with { ssr: false } in Next.js for components that rely on browser APIs: `const MyComponent = dynamic(() => import('./MyComponent'), { ssr: false })` -
Ensure client and server render the same markup by checking for browser environment before rendering: `if (typeof window === 'undefined') return null;` or using `useEffect` to set state after mount with a loading state.
无效尝试
常见但无效的做法:
-
Adding suppressHydrationWarning prop to root element
60% 失败
This only suppresses the warning, doesn't fix the underlying mismatch. The UI may still flash or break.
-
Using useEffect to set state after mount without conditional rendering
50% 失败
Doesn't prevent the initial mismatch during hydration; only fixes subsequent updates.
-
Disabling SSR entirely for the component
40% 失败
Overly aggressive; loses SSR benefits and may cause layout shift.