react runtime_error ai_generated true

错误: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

其他格式: JSON · Markdown 中文 · English
92%修复率
87%置信度
1证据数
2023-04-12首次发现

版本兼容性

版本状态引入弃用备注
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).

generic

官方文档

https://reactjs.org/docs/portals.html

解决方案

  1. 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);
  2. 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.
  3. 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); }, []);

无效尝试

常见但无效的做法:

  1. 90% 失败

    Refs are null during initial render; the container must exist in the DOM before createPortal runs.

  2. 85% 失败

    The element is not attached to the DOM, so it's not a valid container for a portal.

  3. 75% 失败

    Timers are unreliable and may still run before the DOM is ready; also causes race conditions.