首頁  >  文章  >  web前端  >  如何解決 React 綁定回呼函數時出現「this.setState is not a function」錯誤?

如何解決 React 綁定回呼函數時出現「this.setState is not a function」錯誤?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-24 05:03:30891瀏覽

How to Resolve

React 中的錯誤:「this.setState 不是函數」

當嘗試在未綁定的回呼函數中存取this.setState 時,通常會發生此錯誤正確的上下文。在 React 中,this 指的是元件實例,必須維護正確的上下文來存取其方法(如 setState)。

在給定的程式碼片段中,問題出現在VK API 呼叫的回呼函數中:

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);
    }
});

回呼函數是在不同的作用域中定義的,而this 不引用組件實例。要解決此問題,需要將回呼函數綁定到正確的上下文:

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));

透過將回呼函數綁定到this,我們確保this 引用回調中的元件實例,從而允許我們存取this. setState。

在某些情況下,可能需要綁定啟動和 API 呼叫:

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');

這確保 this 在整個過程中引用元件實例,包括啟動和 API 呼叫。

以上是如何解決 React 綁定回呼函數時出現「this.setState is not a function」錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn