Can't perform a React state update on an unmounted component报错解决

目录
  • 总览
  • isMounted
  • 提取

总览

为了解决"Warning: Can't perform a React state update on an unmounted component" ,可以在你的useEffect钩子中声明一个isMounted布尔值,用来跟踪组件是否被安装。一个组件的状态只有在该组件被挂载时才会被更新。

import {useState, useEffect} from 'react';
const App = () => {
  const [state, setState] = useState('');
  useEffect(() => {
    // ️ set isMounted to true
    let isMounted = true;
    async function fetchData() {
      const result = await Promise.resolve(['hello', 'world']);
      // ️ only update state if component is mounted
      if (isMounted) {
        setState(result);
      }
    }
    fetchData();
    return () => {
      // ️ when component unmounts, set isMounted to false
      isMounted = false;
    };
  }, []);
  return (
    <div>
      <h2>State: {JSON.stringify(state)}</h2>
    </div>
  );
};
export default App;

当我们试图更新一个未挂载的组件的状态时,会出现"无法在未挂载的组件上执行React状态更新"的警告。

isMounted

摆脱该警告的直截了当的方式是,在useEffect钩子中使用isMounted布尔值来跟踪组件是否被挂载。

useEffect中,我们初始化isMounted布尔值为true

我们的fetchData 函数执行一些异步的任务,最常见的是一个API请求,并根据响应来更新状态。

然而,需要注意的是,我们只有当isMounted变量被设置为true时,才会更新状态。

async function fetchData() {
  const result = await Promise.resolve(['hello', 'world']);
  // ️ only update state if component is mounted
  if (isMounted) {
    setState(result);
  }
}

这可以帮助我们避免警告,因为如果组件没有挂载,我们就不会更新状态。

当组件卸载时,从useEffect钩子返回的函数会被调用。

return () => {
  // ️ when component unmounts, set isMounted to false
  isMounted = false;
};

我们设置isMounted变量为false,表示该组件不再挂载。如果fetchData函数在组件卸载时被调用,if代码块不会执行是因为isMounted设置为false

async function fetchData() {
  const result = await Promise.resolve(['hello', 'world']);
  // ️ only update state if component is mounted
  if (isMounted) {
    setState(result);
  }
}

提取

如果经常这样做,可以将逻辑提取到可重用的钩子中。

import {useState, useEffect, useRef} from 'react';
// ️ extract logic into reusable hook
function useIsMounted() {
  const isMounted = useRef(false);
  useEffect(() => {
    isMounted.current = true;
    return () => {
      isMounted.current = false;
    };
  });
  return isMounted;
}
const App = () => {
  const [state, setState] = useState('');
  // ️ use hook
  const isMountedRef = useIsMounted();
  useEffect(() => {
    async function fetchData() {
      const result = await Promise.resolve(['hello', 'world']);
      // ️ only update state if component is mounted
      if (isMountedRef.current) {
        setState(result);
      }
    }
    fetchData();
  }, [isMountedRef]);
  return (
    <div>
      <h2>State: {JSON.stringify(state)}</h2>
    </div>
  );
};
export default App;

useRef()钩子可以传递一个初始值作为参数。该钩子返回一个可变的ref对象,其.current属性被初始化为传递的参数。

我们在useIsMounted钩子中跟踪组件是否被挂载,就像我们直接在组件的useEffect钩子中做的那样。

需要注意的是,在fetchData函数中,我们必须检查isMountedRef.current 的值,因为ref上的current属性是ref的实际值。

翻译原文链接:bobbyhadz.com/blog/react-…

以上就是Can't perform a React state update on an unmounted component报错解决的详细内容,更多关于React state update报错的资料请关注我们其它相关文章!

(0)

相关推荐

  • React报错Type '() => JSX.Element[]' is not assignable to type FunctionComponent

    目录 总览 React片段 React.Fragment div 总结 总览 当我们尝试从函数组件中返回元素组成的数组时,会产生"Type '() => JSX.Element[]' is not assignable to type FunctionComponent"错误.为了解决该错误,可以将元素数组包裹在React片段中. 这里有个示例用来展示错误是如何发生的. // App.tsx import React from 'react'; // ️ Type '() =&g

  • Objects are not valid as a React child报错解决

    目录 总览 map JSON.stringify Date 花括号 async 总结 总览 当我们尝试在JSX代码中,直接渲染对象或者数组时,会产生"Objects are not valid as a React child"错误.为了解决该错误,在JSX代码中,使用map()方法来渲染数组或者访问对象的属性. 下面是错误如何发生的示例. export default function App() { const employees = [ {id: 1, name: 'Alice'

  • 解决React报错React.Children.only expected to receive single React element child

    目录 总览 React片段 DOM元素 总览 当我们把多个子元素传递给一个只期望有一个React子元素的组件时,会产生"React.Children.only expected to receive single React element child"错误.为了解决该错误,将所有元素包装在一个React片段或一个封闭div中. 这里有个示例来展示错误是如何发生的. // App.js import React from 'react'; function Button(props)

  • 解决React报错No duplicate props allowed

    目录 总览 className 总结 总览 当我们为相同的组件传递相同的属性多次时,就会导致"No duplicate props allowed"警告.为了解决该警告,请确保只传递一次该属性.比如说,如果传递多次className属性,将它们连接成一个空格分隔的字符串. 下面的示例用来展示如何导致警告的. const App = () => { // ️ JSX elements cannot have multiple attributes with the same nam

  • React报错Function components cannot have string refs

    目录 总览 useRef 不会重新渲染 总览 当我们在一个函数组件中使用一个字符串作为ref时,会产生"Function components cannot have string refs"错误.为了解决该错误,使用useRef()钩子来得到一个可变的ref对象,这样你就可以在组件中作为ref使用. 这里有个示例用来展示错误是如何发生的. // App.js export default function App() { // A string ref has been found

  • 解决React报错Property 'X' does not exist on type 'HTMLElement'

    目录 总览 类型断言 总结 总览 在React中,当我们试图访问类型为HTMLElement 的元素上不存在的属性时,就会发生Property 'X' does not exist on type 'HTMLElement'错误.为了解决该错误,在访问属性之前,使用类型断言来正确地类型声明元素. 这里有三个例子来展示错误是如何发生的. // App.tsx import {useEffect} from 'react'; export default function App() { useEf

  • React报错Too many re-renders解决

    目录 总览 传递函数 传递依赖 移入依赖 传递对象属性 记忆值 总览 产生"Too many re-renders. React limits the number of renders to prevent an infinite loop"错误有多方面的原因: 在一个组件的渲染方法中调用一个设置状态的函数. 立即调用一个事件处理器,而不是传递一个函数. 有一个无限设置与重渲染的useEffect钩子. 这里有个示例来展示错误是如何发生的: import {useState} fro

  • React Hook 'useEffect' is called in function报错解决

    目录 总览 声明组件 声明自定义钩子 总结 总览 为了解决错误"React Hook 'useEffect' is called in function that is neither a React function component nor a custom React Hook function",可以将函数名的第一个字母大写,或者使用use作为函数名的前缀.比如说,useCounter使其成为一个组件或一个自定义钩子. 这里有个示例用来展示错误是如何发生的. // App.j

  • 解决React hook 'useState' cannot be called in a class component报错

    目录 总览 函数组件 类组件中使用setState() 总览 当我们尝试在类组件中使用useState 钩子时,会产生"React hook 'useState' cannot be called in a class component"错误.为了解决该错误,请将类组件转换为函数组件.因为钩子不能在类组件中使用. 这里有个例子用来展示错误是如何发生的. // App.js import {useState, useEffect} from 'react'; class Example

  • React报错解决之ref返回undefined或null

    目录 总览 useEffect 事件 总结 总览 当我们试图在其对应的DOM元素被渲染之前访问其current属性时,React的ref通常会返回undefined或者null.为了解决该问题,可以在useEffect钩子中访问ref,或者当事件触发时再访问ref. import {useRef, useEffect} from 'react'; export default function App() { const ref = useRef(); console.log(ref.curre

  • React hook 'useState' is called conditionally报错解决

    目录 总览 顶层调用 总览 当我们有条件地使用useState钩子时,或者在一个可能有返回值的条件之后,会产生"React hook 'useState' is called conditionally"错误.为了解决该错误,将所有React钩子移到任何可能油返回值的条件之上. 这里有个例子用来展示错误是如何发生的. import React, {useState} from 'react'; export default function App() { const [count,

  • 解决React报错Parameter 'props' implicitly has an 'any' type

    目录 总览 安装类型文件 声明类型 泛型 重新安装 总览 当我们没有为函数组件或者类组件的props声明类型,或忘记为React安装类型声明文件时,会产生"Parameter 'props' implicitly has an 'any' type"错误.为了解决这个错误,在你的组件中明确地为props对象设置一个类型. 安装类型文件 你首先要确定的是你已经安装了React类型声明文件.在项目的根目录下打开终端,并运行以下命令. # ️ with NPM npm install --s

  • React报错之Parameter event implicitly has an any type解决

    目录 引言 总览 设置类型 逃生舱any 确定类型 引言 原文链接:bobbyhadz.com/blog/react-… 作者:Borislav Hadzhiev 正文从这开始~ 总览 当我们不在事件处理函数中为事件声明类型时,会产生"Parameter 'event' implicitly has an 'any' type"错误.为了解决该错误,显示地为event参数声明类型. 比如说,在input元素上,将处理change事件声明类型为React.ChangeEvent<H

  • 解决React报错React Hook useEffect has a missing dependency

    目录 总览 禁用规则 依赖移入 依赖移出 useMemo useCallback 总览 当useEffect钩子使用了一个我们没有包含在其依赖数组中的变量或函数时,会产生"React Hook useEffect has a missing dependency"警告.为了解决该错误,禁用某一行的eslint规则,或者将变量移动到useEffect钩子内. 这里有个示例用来展示警告是如何发生的. // App.js import React, {useEffect, useState}

  • 解决React报错Cannot find namespace context

    目录 总览 tsx 安装@types/包 手动添加 总览 在React中,为了解决"Cannot find namespace context"错误,在你使用JSX的文件中使用.tsx扩展名,在你的tsconfig.json文件中把jsx设置为react-jsx,并确保为你的应用程序安装所有必要的@types包. 这里有个例子来展示错误是如何发生的. // App.ts import React from 'react'; interface UserCtx { first: stri

随机推荐