错误:元素类型无效:期望一个字符串(用于内置组件)或一个类/函数(用于复合组件),但得到了对象。请检查 `App` 的 render 方法。
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of `App`.
ID: react/invalid-array-child
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| React 16.8+ | active | — | — | — |
| React 17.0.2 | active | — | — | — |
| React 18.2.0 | active | — | — | — |
根因分析
组件的 render 方法返回了一个包含非 React 元素对象的数组,例如纯 JavaScript 对象或未渲染的组件类,而不是有效的 React 元素。
English
A component's render method returned an array containing non-React-element objects, such as plain JavaScript objects or unrendered component classes, instead of valid React elements.
官方文档
https://reactjs.org/docs/error-decoder.html/?invariant=31解决方案
-
If you meant to render a list of components, ensure each item is a React element: data.map(item => <Component key={item.id} />). If you meant to display an object, use JSON.stringify(object) or access specific properties. -
Check that you are not accidentally passing a component class instead of an instance: <Component /> not Component alone.
无效尝试
常见但无效的做法:
-
Wrapping the object in a <div> or fragment
40% 失败
If the object is not a valid React element, wrapping it won't fix the underlying issue—it will just produce a different error or render nothing.
-
Using JSON.stringify on the object
60% 失败
This converts the object to a string, which may be displayed but is not a valid React child and can cause hydration mismatches.
-
Importing the component as default instead of named
50% 失败
If the object is a plain JS object (e.g., from an API), no import style will make it a valid component.