Error log – “Cannot read property ‘function’ of undefined…” or “Uncaught TypeError: Cannot read property ‘state’ of null” in React.

At launch academy we are still using react 15, and this error recently started popping up for me in places I had never seen it before. The cause of this error is that functions declared within a component, between the outside of both the return and constructor methods are not specifically bound to any ‘this.’ If you attempt to use a setState in one of these functions when it is unbound you will get the “Uncaught TypeError: Cannot read property ‘state’ of null” error. If you pass one of these unbound functions down to a child it will try to modify the child’s state – not the parent’s state.

That is the cause of the error, but not the reason I suddenly started seeing it recently. That reason is that v15 doesn’t allow es6 arrow functions as class properties (the official name of what I described above) so I had to write it using the older style syntax. for reference:

// ES6 - autobinds on react v16 and newer
myFunction = (props) => {
...
}

// Old style - needs to be manually bound in the constructor.
myFunction() {
...
}

And just in case you got this far and don’t know how to bind a method – here you go!

//put this before the constructor closing brace
this.myFunction = this.myFunction.bind(this)

Tell me what you think.

This site uses Akismet to reduce spam. Learn how your comment data is processed.