UseEffect无法执行状态更新

发布于 2025-01-14 02:16:42 字数 1033 浏览 1 评论 0原文

我收到此 UseEffct 错误,导致我的窗口呈现空页面 error ="无法对已卸载的组件执行 React 状态更新。这是一个空操作,但它表明应用程序中存在内存泄漏。要修复此问题,请取消 useEffect 清理函数中的所有订阅和异步任务。"

我的组件代码

import React, { useEffect, useState } from "react";
import { instance } from "../Data/axios";

const Row = ({ title, fetchURL }) => {
  const [movies, setMovies] = useState([]);
  //  A snippet of code that runs on a certain condition
  useEffect(() => {
    async function fetchData() {
      const data = await instance.get(fetchURL);
      setMovies(data.data.results);
    }
    fetchData();
  }, [fetchURL]);

  const base_url = "https://image.tmdb.org/t/p/original/";

  console.log(movies);
  return (
    <div className="rows">
      <h3>{title}</h3>
      <div className="rows_poster">
        {movies.map((movie) => {
          <div key={movie.id}>
            <img src={`${base_url}${movie.poster_path}`} />
          </div>;
        })}
      </div>
    </div>
  );
};

export default Row;

I am getting this UseEffct error that causes my window to render an empty page
error ="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."

my Component Code

import React, { useEffect, useState } from "react";
import { instance } from "../Data/axios";

const Row = ({ title, fetchURL }) => {
  const [movies, setMovies] = useState([]);
  //  A snippet of code that runs on a certain condition
  useEffect(() => {
    async function fetchData() {
      const data = await instance.get(fetchURL);
      setMovies(data.data.results);
    }
    fetchData();
  }, [fetchURL]);

  const base_url = "https://image.tmdb.org/t/p/original/";

  console.log(movies);
  return (
    <div className="rows">
      <h3>{title}</h3>
      <div className="rows_poster">
        {movies.map((movie) => {
          <div key={movie.id}>
            <img src={`${base_url}${movie.poster_path}`} />
          </div>;
        })}
      </div>
    </div>
  );
};

export default Row;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

可是我不能没有你 2025-01-21 02:16:42

这对我有用:

useEffect(() => {
  let mounted = true;
  async function fetchData(){
    const data = await instance.get(fetchURL);
    if (mounted) {
      setMovies(data.data.results);
    }
  };
  fetchData();
  return ()=> {mounted = false}
}, []);

This has worked for me:

useEffect(() => {
  let mounted = true;
  async function fetchData(){
    const data = await instance.get(fetchURL);
    if (mounted) {
      setMovies(data.data.results);
    }
  };
  fetchData();
  return ()=> {mounted = false}
}, []);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文