データを取得するときに、次のエラーが発生します: マウントされていないコンポーネントで React 状態の更新を実行できません。アプリは引き続き動作しますが、React はメモリ リークが発生している可能性があることを示しています。
これは何も実行されませんが、アプリケーションでメモリ リークが発生していることを示しています。修正するには、useEffect クリーンアップ関数ですべてのサブスクリプションと非同期タスクをキャンセルします。"
なぜこの警告が繰り返し表示されるのでしょうか?
私は以下の解決策を調べてみました:
https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
https://developer.mozilla.org/en-US/docs/Web/API/AbortController
しかし、それでも警告が出ていました。
const ArtistProfile = props => {
const [artistData, setArtistData] = useState(null)
const token = props.spotifyAPI.user_token
const fetchData = () => {
const id = window.location.pathname.split("/").pop()
console.log(id)
props.spotifyAPI.getArtistProfile(id, ["album"], "US", 10)
.then(data => {setArtistData(data)})
}
useEffect(() => {
fetchData()
return () => { props.spotifyAPI.cancelRequest() }
}, [])
return (
<ArtistProfileContainer>
<AlbumContainer>
{artistData ? artistData.artistAlbums.items.map(album => {
return (
<AlbumTag
image={album.images[0].url}
name={album.name}
artists={album.artists}
key={album.id}
/>
)
})
: null}
</AlbumContainer>
</ArtistProfileContainer>
)
}
編集:
私の API ファイルに を追加しAbortController()
、 を使用することsignal
で、リクエストをキャンセルできるようになりました。
export function spotifyAPI() {
const controller = new AbortController()
const signal = controller.signal
// code ...
this.getArtist = (id) => {
return (
fetch(
`https://api.spotify.com/v1/artists/${id}`, {
headers: {"Authorization": "Bearer " + this.user_token}
}, {signal})
.then(response => {
return checkServerStat(response.status, response.json())
})
)
}
// code ...
// this is my cancel method
this.cancelRequest = () => controller.abort()
}
私のspotify.getArtistProfile()
見た目はこんな感じ
this.getArtistProfile = (id,includeGroups,market,limit,offset) => {
return Promise.all([
this.getArtist(id),
this.getArtistAlbums(id,includeGroups,market,limit,offset),
this.getArtistTopTracks(id,market)
])
.then(response => {
return ({
artist: response[0],
artistAlbums: response[1],
artistTopTracks: response[2]
})
})
}
しかし、私のシグナルは、解決される個々の API 呼び出しに使用されるため、その約束Promise.all
はできずabort()
、常に状態を設定することになります。
ベストアンサー1
私の場合、コンポーネントのアンマウント時の状態をクリーンにすることが役に立ちました。
const [state, setState] = useState({});
useEffect(() => {
myFunction();
return () => {
setState({}); // This worked for me
};
}, []);
const myFunction = () => {
setState({
name: 'Jhon',
surname: 'Doe',
})
}