Search code examples
reactjsbabeljsstyled-componentsmobxmobx-react

React "Uncaught Invariant Violation: Element type is invalid" with multiple (up-to-date) 3rd-party react libraries


I'm building a very basic react app as a starting point for new projects and trying to integrate Mobx and Styled Components. The problem I'm running into is that any time I try to include a styled component or react component wrapped with mobx observer in my react tree, I'm getting the following error:

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

I've updated to the latest version of every relevant library and upgraded to the latest versions of node and npm (currently 15.2.0 and 7.0.8, respectively). I've been running into this for a while (with older versions) and am completely stumped about a solution. I'm assuming this has to do with my build/bundle process so I've linked the relevant files below. Happy to include any other files that might be helpful. Any pointers are much appreciated!

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")
)

Also worth noting: My googling of this error mostly suggests import issues, but I'm fairly certain that's not the problem in this case.


Solution

  • I finally figured this out. For some reason there was a node_modules dir in the app directory where my JS files live (one level down from the main package.json and node_modules). For some other reason, webpack/babel seemed to be bundling in an older version of react from that directory in addition to the newer one and that was causing the errors.

    The thing that gave it away was that the aggregated LICENSE.txt file that webpack/babel was outputting contained licenses from both versions of react. I searched my whole project directory for the version string of the older react and found the rogue node_modules.