错误:Portal 容器不是有效的 DOM 元素。请确保在调用 createPortal 之前容器元素已存在。
Error: The portal container is not a valid DOM element. Make sure the container element exists before calling createPortal.
ID: react/portal-container-not-mounted
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| React 16.0+ | active | — | — | — |
| React 17.x | active | — | — | — |
| React 18.x | active | — | — | — |
根因分析
ReactDOM.createPortal 被调用时传递了一个 null 或 undefined 的容器,通常是因为目标 DOM 元素尚未挂载(例如 document.getElementById('portal-root') 返回 null)。
English
ReactDOM.createPortal is called with a container that is null or undefined, usually because the target DOM element hasn't been mounted yet (e.g., document.getElementById('portal-root') returns null).
官方文档
https://reactjs.org/docs/portals.html解决方案
-
Ensure the container element exists in the HTML before the React app mounts. Example: <div id="portal-root"></div> in index.html, then use const portalRoot = document.getElementById('portal-root'); ReactDOM.createPortal(children, portalRoot); -
Use useEffect to create the portal after the component mounts: useEffect(() => { setContainer(document.getElementById('portal-root')); }, []); Then conditionally render the portal only when container is not null. -
For dynamic containers, create the container element in useEffect and append it to document.body: useEffect(() => { const el = document.createElement('div'); document.body.appendChild(el); setContainer(el); return () => document.body.removeChild(el); }, []);
无效尝试
常见但无效的做法:
-
90% 失败
Refs are null during initial render; the container must exist in the DOM before createPortal runs.
-
85% 失败
The element is not attached to the DOM, so it's not a valid container for a portal.
-
75% 失败
Timers are unreliable and may still run before the DOM is ready; also causes race conditions.