react runtime_error ai_generated true

警告: ReactDOM: 期望 `dangerouslySetInnerHTML` 是一个字符串,但得到了 `object`。

Warning: ReactDOM: Expected `dangerouslySetInnerHTML` to be a string, but got `object` instead.

ID: react/warning-react-dom-production-minification-issue

其他格式: JSON · Markdown 中文 · English
93%修复率
84%置信度
1证据数
2024-05-10首次发现

版本兼容性

版本状态引入弃用备注
React 18.2.0 active
React 17.0.2 active
React 16.14.0 active

根因分析

`dangerouslySetInnerHTML` 属性期望一个包含 `__html` 键的对象,其值为字符串,但传递了原始对象或非字符串值,通常是由于误用该属性或传递了组件/JSX 元素而不是 HTML 字符串。

English

The `dangerouslySetInnerHTML` prop expects an object with a `__html` key containing a string, but a raw object or non-string value was passed, often due to misusing the prop or passing a component/JSX element instead of HTML string.

generic

官方文档

https://react.dev/reference/react-dom/components/common#dangerously-setting-the-inner-html

解决方案

  1. Correct the usage: pass an object with __html key containing a sanitized HTML string. Example: <div dangerouslySetInnerHTML={{ __html: '<p>Hello</p>' }} />
  2. If you're trying to render React components dynamically, use a different approach like using a state variable or a render prop instead of dangerouslySetInnerHTML.
  3. Sanitize the HTML string using a library like DOMPurify before passing it to dangerouslySetInnerHTML to prevent XSS attacks.

无效尝试

常见但无效的做法:

  1. Pass a plain string directly to dangerouslySetInnerHTML without the __html wrapper 95% 失败

    dangerouslySetInnerHTML requires an object with __html key; passing a string directly will cause a different error.

  2. Use innerHTML property directly on the DOM element via ref 85% 失败

    Direct DOM manipulation bypasses React's reconciliation and can lead to inconsistencies, but it's also not the intended fix for this warning.

  3. Ignore the warning because the HTML still renders 90% 失败

    The warning indicates a potential XSS vulnerability or incorrect rendering; ignoring it can lead to security issues or broken UI.