Uncaught (in promise) Error: Invalid hook call. Hooks can only be called inside of the body of a function component

Uncaught (in promise) Error: Invalid hook call. Hooks can only be called inside of the body of a function component

App.js:

function App() {
  PreProcess();
  const user = useSelector(selectUser);   // user initialized to null
  return user ?
    (
      <p>{user}</p>
    )
    :
    (<p>Authenticating and Authorizing</p>)
}

export default App;

preProcess.js:

export const PreProcess = async () => {
    await readEnvVars();  // read env vars in local json file
    Auth();   // need environment variables for authentication and authorization
}

auth.js

export const Auth = async () => {
    const dispatch = useDispatch();

    // some logic for authentication and authorization to get the user

    dispatch(setUser(userId));
}

收到错误

Uncaught (in promise) Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

在 auth.js:

const dispatch = useDispatch();

为什么会出现此错误以及如何解决?

挂钩不能在普通 javascript 函数中调用,只能在另一个挂钩或函数组件中调用。

参考:https://reactjs.org/docs/hooks-rules.html

我通过将 const dispatch = useDispatch(); 移动到 App.js 并将调度变量作为参数传递给需要它的方法来解决这个问题。