# 错误：Portal 容器不是有效的 DOM 元素。请确保在调用 createPortal 之前容器元素已存在。

- **ID:** `react/portal-container-not-mounted`
- **领域:** react
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 92%

## 根因

ReactDOM.createPortal 被调用时传递了一个 null 或 undefined 的容器，通常是因为目标 DOM 元素尚未挂载（例如 document.getElementById('portal-root') 返回 null）。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| React 16.0+ | active | — | — |
| React 17.x | active | — | — |
| React 18.x | active | — | — |

## 解决方案

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); }, []);
   ```

## 无效尝试

- **** — Refs are null during initial render; the container must exist in the DOM before createPortal runs. (90% 失败率)
- **** — The element is not attached to the DOM, so it's not a valid container for a portal. (85% 失败率)
- **** — Timers are unreliable and may still run before the DOM is ready; also causes race conditions. (75% 失败率)
