[英]React Warning: Can't perform a React state update on an unmounted component. To fix, cancel all subscriptions
[英]Can't perform a React state update on an unmounted component. (Class component)
問題
我正在用 React Native 編寫應用程序,但無法修復此特定警告。 我知道這是由請求數據引起的,但組件在請求完成之前卸載。 另外,我已經應用了在這里找到的一些解決方案,但無法使其正常工作。 這是我的代碼,我也應用了下面的解決方案。
class PeopleScreen extends React.Component { constructor(props) { super(props); this.state = { listData : [ ] }; } componentDidMount() { // Get list of people. AsyncStorage.getItem("people", function(inError, inPeople) { if (inPeople === null) { inPeople = [ ]; } else { inPeople = JSON.parse(inPeople); } this.setState({ listData : inPeople }); }.bind(this) ); }; render() { return ( )
這是我應用的解決方案:
class PeopleScreen extends React.Component {
_isMounted = false;
constructor(props) {
super(props);
this.state = {
listData : [ ]
};
}
componentDidMount() {
this._isMounted = true;
// Get list of people.
AsyncStorage.getItem("people",
function(inError, inPeople) {
if (inPeople === null) {
inPeople = [ ];
} else {
inPeople = JSON.parse(inPeople);
}
this.setState({ listData : inPeople });
}.bind(this)
);
};
componentWillUnmount() {
this._isMounted = false;
}
render() { return (
)
您需要用 if 語句包裝您的setState
以檢查_isMounted
值是否為真
if(this._isMounted) {
this.setState({ listData : inPeople });
}
我有一種感覺,你在這里的異步代碼可能有問題。 您的回調看起來不錯,技術上應該可行,但我建議您嘗試將回調重寫為Promise resolution 。
最重要的是,您還可以通過刪除額外的if/else
以下列方式改進您的代碼,但這更多的是一種審美偏好。
AsyncStorage.getItem('people').then(async (value) => {
let inPeople = value ? JSON.parse(value) : [];
this.setState({ listData : inPeople });
// or even a one-liner: this.setState({ listData : value ? JSON.parse(value) : [] });
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.