登录后立即登出触发Redux错误:Actions不能有未定义的type属性
Hey there, let's break down this Redux error you're hitting when trying to trigger a logout right after login. That error message is pretty straightforward—Redux is receiving an action where the type property is undefined, and as you suspected, it's almost certainly tied to your logout action or the checkAuthTimeout logic.
Common Causes & Fixes
Let's walk through the most likely issues and how to fix them step by step:
Misspelled or Missing Action Type Constant
TheAUTH_LOGOUTconstant you're referencing might be misspelled, not exported properly, or not imported correctly. Double-check these spots:- In your constants file (e.g.,
actionTypes.js):// Make sure this is correctly exported export const AUTH_LOGOUT = 'AUTH_LOGOUT'; - In your action creator file, confirm you're importing it without typos:
import { AUTH_LOGOUT } from './actionTypes'; // No typos here!
- In your constants file (e.g.,
Broken Logout Action Creator
Yourlogoutaction creator must return an object with a validtypeproperty. If it's missing or pointing to an undefined value, Redux will throw this error. Here's what a correct implementation looks like:export const logout = () => { return { type: AUTH_LOGOUT // This must reference the correctly imported constant }; };Watch out for silly mistakes like misspelling
type(e.g.,typinstead oftype) or forgetting to return the action object entirely.Issues in the
checkAuthTimeoutAsync Action
SincecheckAuthTimeoutis likely a thunk-based async action, make sure you're dispatching the validlogoutaction inside the timeout. Here's a proper version:import { logout } from './authActions'; export const checkAuthTimeout = (expirationTime) => { return (dispatch) => { setTimeout(() => { dispatch(logout()); // Ensure logout() returns a valid action with a type }, expirationTime * 1000); }; };If you're triggering
checkAuthTimeoutright after login, verify you're passing a valid expiration time and that the dispatch is firing the correct action.Login Post-Success Dispatch Logic
When you trigger logout immediately after login, make sure you're dispatching thelogoutaction (either directly or viacheckAuthTimeout) correctly. Avoid dispatching an undefined value or an incomplete action object.
Quick Debugging Trick
Add a console.log(logout()) right before dispatching it—this will show you exactly what action is being sent to Redux. If the output doesn't include a type: "AUTH_LOGOUT" property, that's where your problem lives.
Once you fix these gaps, you should see the AUTH_LOGOUT action pop up in your Redux dev tools as expected!
内容的提问来源于stack exchange,提问作者moderewer

