React use原因:无法对未挂载的组件执行 React 状态更新
2022-08-30 02:44:32
						获取我获得的数据时:无法对未挂载的组件执行 React 状态更新。该应用程序仍然可以工作,但反应表明我可能导致内存泄漏。
这是一个 no-op,但它表示应用程序中存在内存泄漏。要修复此问题,请取消 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.allabort()
 
					 
				 
				    		 
				    		 
				    		