我收到此错误:
index.js:1 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
in Home (at App.js:16)
我在useEffect挂钩中有一个异步访存调用。我知道有一些解决方法,我尝试了一些,但决定使用AbortController方法。但是,我仍然收到错误消息(刷新页面时)
import React, { useState, useEffect } from "react"
import hash from "../auth/hash"
import { useHistory } from "react-router-dom"
const Home = () => {
let history = useHistory()
const [userData, setUserData] = useState(null)
useEffect(() => {
const controller = new AbortController()
const signal = controller.signal
let _token = hash.access_token
// redirects back to the login page if there's not a token -- maybe upgrade error handling in the future
if (!_token) history.push("/")
const spotifyConnect = async () => {
let response = await fetch(
"https://api.spotify.com/v1/me",
{
method: "GET", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, *cors, same-origin
headers: {
Authorization: `Bearer ${_token}`,
},
},
{ signal }
)
setUserData(await response.json())
}
try {
spotifyConnect()
} catch (error) {
console.log(error)
}
return () => controller.abort()
}, [history])
useEffect(() => {
console.log(userData)
}, [userData])
if (!userData) return null
return (
<div className="bg-black p-5 rounded-lg text-center max-w-xs">
<h1 className="text-white text-2xl mb-2">
Welcome to spotify playlist app
</h1>
<img src={userData.images[0].url} alt="profile" />
</div>
)
}
export default Home
答案 0 :(得分:0)
更新:我需要将信号添加到options对象(fetch占用的第二个arg),而不是将其放在自己的对象中并尝试传递fetch 3个参数,所以这就是为什么它不起作用的原因。尽管现在我遇到了其他一些错误:(