如何阻止未安装组件的内存泄漏

How to stop memory leak on unmounted component

我正在尝试使用 axios 获取数据并将获取的数据插入到我的 useState 钩子中,它必须是数组,但是存在内存泄漏错误,我尝试了所有方法,使用清理函数我也尝试了 new AbortController(); 取消抓取,还尝试放入 isMount 布尔变量来阻止该错误,但它仍然弹出相同的错误

这是我的组件代码一切都很简单

import { useEffect, useState, FC, useRef } from "react"
import Card from "../Dashboard/Card"
import axios from "axios"
import "../../less/profile-styles/user-blogs-styles.css"
import "../../less/dashboard-style/loader.css"

const UserBlogs: FC<{ id: string; name: string }> = ({ name, id }) => {
  const [userBlogs, setUserBlogs] = useState<any>([])
  const [isLoading, setIsLoading] = useState<boolean>(false)

  useEffect(() => {

    let abortController = new AbortController();
    // let isMinted: boolean = true

    setIsLoading(true)
    axios
      .get(`http://localhost:5000/blog/blog-user/${id}`)
      .then((response) => {  //also I inserted here if statement, to check if isMunted true or not, if it true perform that inserting data in useState
          setUserBlogs(
            response.data.map((blog: any) => {
              return {
                title: blog.blog.title,
                img: blog.blog.file,
                liked: blog.blog.likes,
                mainContent: blog.blog.mainContent,
                authorID: blog.userID,
                blogId: blog.blog._id
              }
            })
          )
        
        setIsLoading(false)
      })
      .catch((err) => console.log(err))


    return () => {
      abortController.abort()
      //isMunted = false
    }
  }, [])

  console.log(userBlogs)

  return (
    <div className="user-blogs">
      <h1>{name}'s blogs</h1>
      <div className="dashboard-container">
      {
          userBlogs.map((blog: any) => {
            return (
              <Card
                title={blog.title}
                img={blog.img}
                liked={blog.likes}
                mainContent={blog.mainContent}
                authorID={blog.userId}
                blogId={blog._id}
                likeSystem={() => {}}
              />)
            }
          )
        }
      </div>
    </div>
  )
}

export default UserBlogs

这里有错误

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.

您实际上并未将 abortcontroller.signal 设置为您的 axios.get 调用。

these axios docs

axios.get('/foo/bar', {
    signal: abortController.signal
}).then(...)
...
abortController.abort()