问题描述
升级到 React 17 后,应用无法在某些平台上加载。例如,它在现代 Chrome 中仍然运行良好,但在旧浏览器中失败。在app入口文件的ReactDOM.render函数中失败,报错如下:
错误:缩小反应错误 #31;访问 https://reactjs.org/docs/error-decoder.html?invariant=31&args[]=object%20wi…ys%20%7B%24%24typeof%2C%20type%2C%20key%2C%20ref%2C%20props%2C%20_owner%7D 获取完整信息或使用非缩小的开发环境获取完整信息 错误和其他有用的警告。
去那里会提供额外的信息:
你刚才遇到的错误全文是: 对象作为 React 子对象无效(找到:带有键的对象 {$$typeof,type,key,ref,props,_owner})。如果你想渲染一个 子集合,请改用数组。
解决方法
事实证明,在那些依赖 core-js 进行 polyfill 的平台上加载失败。脚本加载顺序乱了,所以core-js没有先加载,即使是在入口文件中先导入了。可能是由于可以自动导入 React 的新方式,该功能现在在应用中使用:
presets: [
'@prefix/babel-preset-libx',[
'@babel/preset-react',{
runtime: 'automatic'
}
]
],
检查导致错误的JS对象显示:
Chrome:
$$typeof: Symbol(react.element)
key: null
props: {children: "TEST"}
ref: null
type: "div"
_owner: null
失败的平台:
$$typeof: 60103
key: null
props: Object
ref: null
type: "div"
_owner: null
它似乎与这个问题有关:https://github.com/facebook/react/issues/8379,以及这个 SO 问题:Objects are not valid as a react child (In Internet explorer 11 for React 15.4.1)。
就像那些一样,解决方案是在 webpack.config.js 中指定脚本加载顺序:
entry: [
'core-js',// Should be loaded first
// If applicable: 'react-hot-loader',// This package requires/loads react (but not react-dom).
'react',// Include this to enforce order
'react-dom',// Include this to enforce order
'./client.js' // Path to your app's entry file
]
感谢 https://stackoverflow.com/users/4757672/fran%c3%a7ois-maturel 在 https://stackoverflow.com/a/40928047/1158376 中的解决方案