Cannot read property 'setState' of undefined, when running a function

cannot read property 'value' of undefined
cannot read property 'some' of undefined
cannot read property of undefined subway app
cannot read property of undefined react
cannot read property of undefined angular
cannot read property of null
cannot read property of undefined typescript
cannot read property 'update' of undefined
class App extends Component {
  constructor(){
    super();
    this.state = {
      sideNav: '',
      language: 'en'
    }
  }

  langEn() {
    this.setState({language: 'en'}).bind(this);
    console.log("Language changed to en");
  }

  langEs() {
    this.setState({language: 'es'}).bind(this);
    console.log("Language changed to es");
  }

  render() {

    const mouseEnter = e => {
      this.setState({sideNav: "sideNav sidenav---sidenav---_2tBP sidenav---expanded---1KdUL"});
    }    

    const mouseLeave = e => {
      this.setState({sideNav: "sidenav---sidenav---_2tBP sidenav---collapsed---LQDEv"});
    }


    return (
      <div className="App container">
        <div>
          <SideNav 
            onMouseEnter={mouseEnter} 
            onMouseLeave={mouseLeave}
            className={this.state.sideNav}
            onSelect={(selected) => {
                // Add your code here
            }}
          >
            <SideNav.Nav  defaultSelected="home">
                <NavItem eventKey="home">
                    <NavIcon>
                        <Link to="/"><img src={Dash}/></Link>
                    </NavIcon>
                    <NavText>
                        <Link to="/">Dashboard</Link>
                    </NavText>
                </NavItem>
                <NavItem eventKey="sites">
                    <NavIcon>
                      <Link to="/sites"><img src={Site} /></Link>
                    </NavIcon>
                    <NavText>
                        <Link to="/sites">Sites</Link>
                    </NavText>
                </NavItem>
                <NavItem eventKey="tours">
                  <NavIcon>
                    <Link to="/tours"><img src={Tour}/></Link>
                  </NavIcon>
                  <NavText>
                      <Link to="/tours">Tours</Link>
                  </NavText>
                </NavItem>
                <NavItem eventKey="media">
                    <NavIcon>
                      <Link to="/media"><img src={Media}/> </Link>
                    </NavIcon>
                    <NavText>
                        <Link to="/media">Media</Link>
                    </NavText>
                </NavItem>
                <NavItem eventKey="newSite">
                    <NavIcon>
                        <Link to="/newSite/details"><img src={NewSite} /></Link>
                    </NavIcon>
                    <NavText>
                        <Link to="/newSite/details">Add new Site</Link>
                    </NavText>
                </NavItem>
                <NavItem eventKey="language">
                    <NavIcon>
                        <Link to="/language"><img src={Lang} /></Link>
                    </NavIcon>
                    <NavText>
                        <Link to="/language">Language</Link>
                    </NavText>
                </NavItem>
                <NavItem eventKey="profile">
                    <NavIcon>
                        <Link to="/profile"><img src={Profile} /></Link>
                    </NavIcon>
                    <NavText>
                        <Link to="/profile">Profile</Link>
                    </NavText>
                </NavItem>

            </SideNav.Nav>
            <button onClick={this.langEn}>EN</button>
            <button onClick={this.langEs}>ES</button>
          </SideNav>
        </div>
        <Routes childProps={this.state} />
      </div>
    );
  }
}

export default App;

The error happens when I press one of the two buttons to run the lanEn or lanEs functions. I have tried alternating where they are, placing them in or out of the render() method, removing this using bind. The end goal is change the language state using these buttons and transfer it to different pages using props

You just need to add this piece of code in the constructor:

this.langEn = this.langEn.bind(this);

What the above code does is, it replaces the existing langEn function with a new function with the this context changed to class App.

If you don't want to manually bind it in the constructor, you can go with arrow functions, which has lexical binding.

Avoiding those dang cannot read property of undefined errors , Uncaught TypeError: Cannot read property 'foo' of undefined. The dreaded error we all hit at some point in JavaScript development. Could be� Here is a common scenario. // We want to get the value of an input. varinputVal = document.getElementById("input").value; This will result in Uncaught TypeError: Cannot read property 'value' of null. The reason will be that the element with id inputdoes not exist. Let me break it down in simpler steps; varinput = document.getElementById("input"); input // when this fails, it returns null. input = nullvarinputVal = input.value;// this is the same as the following.

Just simply bind methods in the constructor:

class App extends Component {
  constructor(){
    super();
    this.state = {
      sideNav: '',
      language: 'en'
    }
    this.langEn.bind(this);
    this.langEs.bind(this);
  }

  langEn() {
    this.setState({language: 'en'}).bind(this);
    console.log("Language changed to en");
  }

  langEs() {
    this.setState({language: 'es'}).bind(this);
    console.log("Language changed to es");
  }

  render() {

    const mouseEnter = e => {
      this.setState({sideNav: "sideNav sidenav---sidenav---_2tBP sidenav---expanded---1KdUL"});
    }    

    const mouseLeave = e => {
      this.setState({sideNav: "sidenav---sidenav---_2tBP sidenav---collapsed---LQDEv"});
    }


    return (
      <div className="App container">
...
      <button onClick={this.langEn}>EN</button>
      <button onClick={this.langEs}>ES</button>
...

JavaScript "cannot read property "bar" of undefined, If an object's property may refer to some other object then you can test that for undefined before trying to use its properties: if (thing && thing.foo)� Join the world's most active Tech Community! Welcome back to the World's most active Tech Community!

First, you try to bind this.setState in langEn and langEn. Why?

Second, all this stuff happens because functions have their own context.

Whether use bind for methods call:

...
<button onClick={this.langEn.bind(this)}>EN</button>
...

or use arrow key functions (they have no their own context):

langEn = () => {
  this.setState({language: 'es'}, () => console.log("Language changed to es"));
}

How to avoid 'cannot read property of undefined' errors?, Update: If you use JavaScript according to ECMAScript 2020 or later, see optional chaining. TypeScript has added support for optional chaining in version 3.7. I get this error message "Cannot read property '0' of undefined google chart" when i load my 2 graphs and it only occurs when i load my page for the first time.

Prevent “Cannot read property '…' of undefined” errors with , Every developer who did some JavaScript has got errors like “Cannot read property '…' of undefined”. There is one simple way to prevent them,� everytime when i try to change somthing in the Alertbox they show me “ Please enter a number greater than or equal to 0” or “ cannot read property ‘settings’ of undefined” icon Best answer by Castorr91 21 December 2019, 14:54

TypeError: Cannot read property 'isNextDevCommand' of undefined , Bug report Describe the bug TypeError: Cannot read property ' isNextDevCommand' of undefined options in createServer() do not seem to have � Uncaught TypeError: Cannot read property of undefined In JavaScript. Out of the six primitive types defined in JavaScript, namely boolean, string, symbol, number, Null, and undefined, no other type throws as many errors as Undefined.

TypeError: Cannot read property 'name' of undefined � Issue #10803 , 0.0-beta.7 (from 5.3.18), when I run storybook I see an error. hooks.js:232 Uncaught TypeError: Cannot read property� cannot read property 'guild' of undefined. Code Help. case 'mute': if (message.member.hasPermission ("MUTE_MEMBERS")) { const userMute = message.mentions.users.first (); const memberMute = message.guild.member (userMute); const muteEmbed = new Discord.MessageEmbed () .setColor ('YELLOW') .addField ('**You\'ve been Muted!**') .addField ('Moderator', message.author.tag, false) .addField ('Reason', args [2], false) .addField ('Muted at:', message.createdAt, false) .addField ('Muted In:',

Comments
  • Try using arrow functions instead. Check out this answer from about an hour ago stackoverflow.com/questions/54982653/…
  • It's working now but I have a way of sending this.state.language to my Routes as a prop, but when I press the button to update the state, it doesn't update the route too
  • @TiernO In you current example, the code for setting language state is harcoded to have en as the value always: this.setState({language: 'en'}).bind(this);. Whenever the state changes, it will reset to the same value. That is the reason, it's not updating in prop as well.
  • Oh I understand, so how do i fix it?
  • @TiernO also, setState doesn't return anything. So having the bind statement like this.setState({language: 'en'}).bind(this); may result in an exception since you're trying to bind something which is undefined. You only need this.setState({language: 'en'}) for setting the state.
  • Yes i have removed the bind() from the setState call
  • When I use the bind I get an error saying "Cannot read property "bind" of undefined"
  • @TiernO you should bind not on this.setState, but on the function calling (e.g, langEn). Look the code above.
  • You get the error because you try to bind the undefined method setState of the current function context.