Why does setState callback throw an error: "State updates from the useState() and useReducer() Hooks don't support the second callback argument..."

Why does setState callback throw an error: "State updates from the useState() and useReducer() Hooks don't support the second callback argument..."

我正在尝试创建一个 setState 回调,因为 setState 是异步的,我想之后安全地使用该状态。

function Register(props) {
    const [errMsg, setErrMsg] = useState(null);
    
    const fullNameInputRef = useRef();
    const emailInputRef = useRef();
    const passwordInputRef = useRef();


    function submitHandler(event) {
        event.preventDefault(); //prevents full page reload
        
        const enteredFullName = fullNameInputRef.current.value;
        const enteredEmail= emailInputRef.current.value;
        const enteredPassword = passwordInputRef.current.value;

        axios({
            method: 'post',
            url: 'http://localhost:3000/api/users/register',
            data: {
              username: enteredFullName,
              email: enteredEmail,
              password: enteredPassword
            }
          }).then( (res) => {
              if (res.data.success == false) {
                  setErrMsg(`${res.data.message}`, () => {  /* setState Callback */
                    console.log(errMsg);
                  });
              }
              else { console.log(res)}
          }).catch( (err) => {
              console.log(err)
              setErrMsg("An error has occured. Please try again later")
          });
    
      }

但是回调中的 console.log 不起作用。 (console.log(errMsg);) 我收到以下错误:

Warning: State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect().

我错过了什么?

与错误状态一样,setState 钩子不支持第二个参数,如 class 组件:

// BAD, WRONG API
setErrMsg(`${res.data.message}`, () => console.log(errMsg));

相反,添加 useEffect:

// GOOD
setErrMsg(`${res.data.message}`);

useEffect(() => {
  console.log(errMsg);
}, [errMsg]

完整代码:

function Register(props) {
    const [errMsg, setErrMsg] = useState(null);
    
    ...

    useEffect(() => {
        console.log(errMsg);
    }, [errMsg]


    function submitHandler(event) {
        ...

        axios({ ... }).then((res) => {
              if (res.data.success == false) {
                  setErrMsg(`${res.data.message}`);
              }
              else { console.log(res)}
          }).catch( (err) => {
              console.log(err)
              setErrMsg("An error has occured. Please try again later")
          });
      }

   return <>...</>
}