close

[Solved] React this.setState is not a function

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error React this.setState is not a function in javascript. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How React this.setState is not a function Error Occurs?

Today I get the following error React this.setState is not a function in javascript.

How To Solve React this.setState is not a function Error ?

  1. How To Solve React this.setState is not a function Error ?

    To Solve React this.setState is not a function Error use arrow functions, as arrow functions point to parent scope and this will be available. (substitute of bind technique)

  2. React this.setState is not a function

    To Solve React this.setState is not a function Error use arrow functions, as arrow functions point to parent scope and this will be available. (substitute of bind technique)

Solution 1

The callback is made in a different context. You need to bind to this in order to have access inside the callback:

VK.api('users.get',{fields: 'photo_50'},function(data){
    if(data.response){
        this.setState({ //the error happens here
            FirstName: data.response[0].first_name
        });
        console.info(this.state.FirstName);
    }

}.bind(this));

EDIT: Looks like you have to bind both the init and api calls:

VK.init(function(){
        console.info("API initialisation successful");
        VK.api('users.get',{fields: 'photo_50'},function(data){
            if(data.response){
                this.setState({ //the error happens here
                    FirstName: data.response[0].first_name
                });
                console.info(this.state.FirstName);
            }

        }.bind(this));
    }.bind(this), function(){
    console.info("API initialisation failed");

    }, '5.34');

Solution 2

use arrow functions, as arrow functions point to parent scope and this will be available. (substitute of bind technique)

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also Read

Leave a Comment