最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function error - Stack Overflow

programmeradmin7浏览0评论

Warning: Can't perform a React state update on an unmounted ponent. 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.

useEffect(() => {
    const unsubscribe = streamCourses({
      next: (querySnapshot) => {
        const task = querySnapshot.docs.map((docSnapshot) => 
            mapDocTask(docSnapshot)
          );
        setCourseDetails(task);
      },
      error: (error) => console.log(error),
    });
    return unsubscribe;
  }, [setCourseDetails]);

Warning: Can't perform a React state update on an unmounted ponent. 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.

useEffect(() => {
    const unsubscribe = streamCourses({
      next: (querySnapshot) => {
        const task = querySnapshot.docs.map((docSnapshot) => 
            mapDocTask(docSnapshot)
          );
        setCourseDetails(task);
      },
      error: (error) => console.log(error),
    });
    return unsubscribe;
  }, [setCourseDetails]);
Share Improve this question asked Oct 27, 2021 at 6:27 P A T HimarangaP A T Himaranga 1111 gold badge2 silver badges5 bronze badges 2
  • HI please include some details of the scenario you are having with. It will help us understand your question – German Commented Oct 27, 2021 at 7:11
  • Why is there a setCourseDetails there? And what does it do? – Mario Nikolaus Commented Oct 27, 2021 at 7:36
Add a ment  | 

1 Answer 1

Reset to default 5

I had a similar issue to this. What I had to do to solve it was two things:

(1) I created a State boolean isMounted which was set to true by default and was used to wrap the contents of my useEffects so that the contents of my useEffects would only run if the screen was mounted.

(2) I created a useEffect dedicated solely to cleanup. Meaning this useEffect had nothing besides a return statement in it which set the various State variables I had to their default values.

Example:

useEffect(() => {
    if (isMounted) {
        const unsubscribe = streamCourses({
          next: (querySnapshot) => {
            const task = querySnapshot.docs.map((docSnapshot) => 
                mapDocTask(docSnapshot)
              );
            setCourseDetails(task);
          },
          error: (error) => console.log(error),
        });
        return unsubscribe;
    }
  }, [setCourseDetails]);

useEffect(() => {
    return () => {
        setCourseDetails(null);
        setIsMounted(false);
    }
}, []);

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论