1
votes

I created a simple app to demonstrate the issue with calling a function with the wrong context in React class components.

Here is the error message I get on my local machine:

TypeError: undefined is not an object (evaluating 'this.setState')

And here is the error message I get on CodeSandbox for the same error:

TypeError this.setState is not a function.

I understand that both these errors point to the same thing, but why are they showing different messages? I made sure that the versions of React and react-scripts are the same, so that's not the issue. Also, I tried downloading the code from CodeSandbox and running it locally, and I still got the first error message.

What gives?

You can see the sandbox here.

2
Are you transpiling to the same version of ES? Also, what is the second error on CodeSandbox? - zhulien
@zhulien Yes, that's how it should be. I added a link to the sandbox in the question. You can also try downloading the files to your computer and running them locally. When I run it locally with the same configuration, it produces a different error message. - Evrim Persembe

2 Answers

0
votes

They are using different Javascript engines. Error messaging will vary from engine to engine.

https://en.wikipedia.org/wiki/List_of_ECMAScript_engines

0
votes

this works on my end

import React from "react";

export default class Counter extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      counter: 0
    };
  }

  handleIncrementClick() {
    this.setState(({ counter }) => ({
      counter: counter + 1
    }));
  }

  render() {
    const { counter } = this.state;

    return (
      <div>
        <p>Counter value is: {counter}</p>
        <p>
          <button onClick={() => this.handleIncrementClick(this)}>Increment Counter</button>
        </p>
      </div>
    );
  }
}