错误:无法对卸载的组件执行 React 状态更新

IT技术 reactjs
2021-05-02 12:26:54

这是完全错误

警告:无法对卸载的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要修复,请取消 useEffect 清理函数中的所有订阅和异步任务。在注册页面

这是我的 siguppage.js 文件

import React, { useState } from 'react'
import { withFirebase } from '../firebase/Context'
import { useHistory } from 'react-router-dom'
import { compose } from 'recompose'
import withAuthUser from '../UserData/withAuthUser'

const SignUpPage = (props) => {
    const [Email, setEmail] = useState('')
    const [PasswordOne, setPasswordOne] = useState('')
    const [PasswordTwo, setPasswordTwo] = useState('')
    const [UserName, setUserName] = useState('')
    const [error, setError] = useState('')
    let history = useHistory()
    const [AuthUser, setAuthUser] = props.AuthUser()

    const onSubmit = () => {
        props.firebase
            .createUserWithEmailAndPassword(Email, PasswordOne)
            .then((authUser) => {
                history.push('/home')
                setAuthUser(authUser)
            })
            .catch((error) => {
                setError(error)
                console.log(error)
            })
    }

    const IsInvalid =
        Email === '' ||
        PasswordOne === '' ||
        PasswordTwo === '' ||
        UserName === '' ||
        PasswordTwo !== PasswordOne

    return (
        <div>
            <h1>Sign Up</h1>

            <input
                type='text'
                placeholder='UserName'
                value={UserName}
                onChange={(UserName) => {
                    const { value } = UserName.target
                    setUserName(value)
                }}
            ></input>
            <input
                type='text'
                placeholder='email'
                value={Email}
                onChange={(Email) => {
                    const { value } = Email.target
                    setEmail(value)
                }}
            ></input>
            <input
                type='password'
                placeholder='PasswordOne'
                value={PasswordOne}
                onChange={(pass) => {
                    const { value } = pass.target
                    setPasswordOne(value)
                }}
            ></input>
            <input
                type='password'
                placeholder='PasswordTwo'
                value={PasswordTwo}
                onChange={(pass) => {
                    const { value } = pass.target
                    setPasswordTwo(value)
                }}
            ></input>
            <button disabled={IsInvalid} onClick={onSubmit} type='submit'>
                Submit
            </button>

            {error && <p>{error.message}</p>}
        </div>
    )
}

export default compose(withFirebase, withAuthUser)(SignUpPage)

我为此使用了 HOC,我通过了props.AuthUserwithAuthUser 类似的东西

const withAuthUser = (Component) => (props) => {
    return (
        <AuthUserContext.Consumer>
            {(AuthUser) => <Component {...props} AuthUser={AuthUser}></Component>}
        </AuthUserContext.Consumer>
    )
}

AuthUser 是一个函数

export const Value = () => {
    const [AuthUser, setAuthUser] = useState(null)
    return [AuthUser, setAuthUser]
}

我将此函数传递给了 main 中的 Provider 使用上下文 index.js

所以我试图AuthUser通过调用 props.setAuthUser来更新状态,但它给出了这个错误..

3个回答

当您在离开屏幕后尝试更新屏幕内的状态时,会出现此错误。为了解决这个问题,我们需要一个使用useEffect钩子的清理函数

所以你SignupPage.js应该看起来像这样

import React, { useEffect, useState } from "react";
import { withFirebase } from "../firebase/Context";
import { useHistory } from "react-router-dom";
import { compose } from "recompose";
import withAuthUser from "../UserData/withAuthUser";

const SignUpPage = (props) => {
  const [Email, setEmail] = useState("");
  const [PasswordOne, setPasswordOne] = useState("");
  const [PasswordTwo, setPasswordTwo] = useState("");
  const [UserName, setUserName] = useState("");
  const [error, setError] = useState("");
  let history = useHistory();
  const [AuthUser, setAuthUser] = props.AuthUser();

  useEffect(() => {
    return () => {};
  }, []);

  const onSubmit = () => {
    props.firebase
      .createUserWithEmailAndPassword(Email, PasswordOne)
      .then((authUser) => {
        history.push("/home");
        setAuthUser(authUser);
      })
      .catch((error) => {
        setError(error);
        console.log(error);
      });
  };

  const IsInvalid =
    Email === "" ||
    PasswordOne === "" ||
    PasswordTwo === "" ||
    UserName === "" ||
    PasswordTwo !== PasswordOne;

  return (
    <div>
      <h1>Sign Up</h1>

      <input
        type="text"
        placeholder="UserName"
        value={UserName}
        onChange={(UserName) => {
          const { value } = UserName.target;
          setUserName(value);
        }}
      ></input>
      <input
        type="text"
        placeholder="email"
        value={Email}
        onChange={(Email) => {
          const { value } = Email.target;
          setEmail(value);
        }}
      ></input>
      <input
        type="password"
        placeholder="PasswordOne"
        value={PasswordOne}
        onChange={(pass) => {
          const { value } = pass.target;
          setPasswordOne(value);
        }}
      ></input>
      <input
        type="password"
        placeholder="PasswordTwo"
        value={PasswordTwo}
        onChange={(pass) => {
          const { value } = pass.target;
          setPasswordTwo(value);
        }}
      ></input>
      <button disabled={IsInvalid} onClick={onSubmit} type="submit">
        Submit
      </button>

      {error && <p>{error.message}</p>}
    </div>
  );
};

export default compose(withFirebase, withAuthUser)(SignUpPage);

试试这个,让我知道。

您正在尝试在未安装的组件上设置状态。

const onSubmit = () => {
  props.firebase
    .createUserWithEmailAndPassword(Email, PasswordOne)
    .then((authUser) => {
      history.push("/home"); //This causes the current component to unmount
      setAuthUser(authUser); //This is an async action, you are trying to set state on an unmounted component.
    })
    .catch((error) => {
      setError(error);
      console.log(error);
    });
};

一个未安装的组件是您的 SignUpPage 组件。当组件在安装时使用它时,找到停止 onSubmit 的方法。首先,当使用这个函数和这个 onSubmit 的组件挂载时运行一个清理函数,因此将清理函数放在 onSubmit 中并返回它,以便在 useEffect 中返回一个值,该值是一个函数,然后当使用的组件这个 useEffect 它会触发返回的清理函数。您可以创建类似 AbortController() 的内容来捕获错误并更新状态。