【问题标题】:React "Uncaught Invariant Violation: Element type is invalid" with multiple (up-to-date) 3rd-party react libraries使用多个(最新)第 3 方反应库反应“未捕获的不变违规:元素类型无效”
【发布时间】:2021-02-25 21:57:43
【问题描述】:

我正在构建一个非常基本的 React 应用程序作为新项目的起点,并尝试集成 Mobx 和 Styled Components。我遇到的问题是,每当我尝试在我的反应树中包含一个样式组件或用 mobx observer 包装的反应组件时,我都会收到以下错误:

Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.`

我已经更新到每个相关库的最新版本,并升级到 node 和 npm 的最新版本(目前分别为 15.2.0 和 7.0.8)。我已经遇到了一段时间(使用旧版本)并且完全不知道解决方案。我假设这与我的构建/捆绑过程有关,所以我在下面链接了相关文件。很高兴包含任何其他可能有用的文件。任何指针都非常感谢!

import ReactDOM from "react-dom"
import { observer } from "mobx-react"
import { makeAutoObservable } from "mobx"

class Store {
  counter = 1

  constructor() {
    makeAutoObservable(this)
  }

  get counterPlusOne () {
    return this.counter + 1
  }

  incrementCounter = () => {
    this.counter++
  }
}

const store = new Store()

// Removing `observer` on the next line removes the error but fails to integrate mobx
const App = observer(({store}) => {
  return (
    <div>
      <p className="counter-state">Counter is at: {store.counter}</p>
      <button onClick={store.incrementCounter}>
        Increment counter
      </button>
      <p className="next-counter-state">
        Clicking the button will set the counter to: {store.counterPlusOne}
      </p>
    </div>
  )
})

ReactDOM.render(
  <App store={store} />,
  document.getElementById("root")
)

另外值得注意的是:我对这个错误的谷歌搜索主要表明存在导入问题,但我相当确定这不是本例中的问题。

【问题讨论】:

    标签: reactjs babeljs styled-components mobx mobx-react


    【解决方案1】:

    您最好分享您的代码(或开发者控制台中的错误日志),而不是配置。但基本上错误元素不应该是一个对象,而是字符串(内置组件名称)或类组件(例如:class MyComp extends Component)

    【讨论】:

    • 我添加了一个完整版本的代码,它在使用 mobx 时会产生错误。我理解错误在说什么——但是当我按照他们的示例进行操作时,这两个库似乎都在返回对象(我已经四次检查我没有犯明显的错误)。
    【解决方案2】:

    我终于想通了。出于某种原因,在我的 JS 文件所在的app 目录中有一个node_modules 目录(主package.jsonnode_modules 的下一层)。出于某些其他原因,webpack/babel 似乎捆绑在该目录中的旧版本 react 中,除了新版本之外,这也是导致错误的原因。

    泄露它的是 webpack/babel 输出的聚合 LICENSE.txt 文件包含来自两个版本的 react 的许可证。我在整个项目目录中搜索了旧 react 的版本字符串,发现了流氓node_modules

    【讨论】:

      猜你喜欢
      • 2016-07-20
      • 2016-08-31
      • 1970-01-01
      • 2016-07-29
      • 2016-03-27
      • 1970-01-01
      • 1970-01-01
      • 2016-04-09
      • 2018-07-19
      相关资源
      最近更新 更多