# 错误：目标容器不是DOM元素。使用createPortal时，第二个参数必须是有效的DOM节点。

- **ID:** `react/portal-target-not-dom-element`
- **领域:** react
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 88%

## 根因

传递给ReactDOM.createPortal的第二个参数不是有效的DOM元素（例如null、undefined或字符串选择器），通常是因为目标元素尚未渲染或选择器不正确。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| React 16.0.0 | active | — | — |
| React 17.0.2 | active | — | — |
| React 18.2.0 | active | — | — |

## 解决方案

1. ```
   Ensure the target DOM element exists before calling createPortal by using a ref or checking if the element is available in useEffect.
   ```
2. ```
   Define the target element in the HTML file (e.g., index.html) and ensure it's present before the React app mounts.
   ```

## 无效尝试

- **Using document.querySelector('#root') without checking if the element exists** — If the DOM element is not yet mounted (e.g., in a component that renders before the target), querySelector returns null. (70% 失败率)
- **Passing a string like '#modal-root' directly to createPortal** — createPortal expects a DOM element, not a CSS selector string. It will throw an error because a string is not a node. (90% 失败率)
- **Using document.getElementById inside a component that runs before the target is rendered** — If the target div is defined in the same component's JSX, it may not exist in the DOM when the portal is created, leading to null. (60% 失败率)
