Fixing React error: Uncaught TypeError: MyMixin is not a function(anonymous function)

When upgrading React, you may be tempted to have your ES6 classes extend Mixin objects (to avoid upgrading these)

For example:

var MyMixin = {
  componentShouldUpdate: function() {
    // some logic
  }
}
 
class MyComponent extends MyMixin {
  constructor() {
    // do some stuff...
    this.state = {}
  }
 
  render() { 
    return (<div></div>)
  }
})

You will get a very cryptic error like so:

Uncaught TypeError: MyMixin is not a function(anonymous function)

This is because “objects” are actually a function (a constructor) with the information for how to construct the object in fn._prototype.

To fix the above error, you can either convert MyMixin to a real class, or make a base class that you can extend that contains the mixins, like so:

class MyComponent extends React.createClass({
  mixins: [MyMixin],
  render: () => {}
}) {
  constructor() {
    // do some stuff...
    this.state = {}
  }
 
  render() { 
    return (<div></div>)
  }
})

Interested in JavaScript? I send out weekly, personalized emails with articles and conference talks. Click here to see an example and subscribe.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *