React Redux集成Redux-Thunk后仍出现Actions类型错误求助
问题解决:Actions must be plain objects 错误排查与修复
错误根源
你的代码里组件内部的useState状态更新函数setUserLocation和Redux导出的action creatorsetUserLocation重名了。当你在handleLocation里调用dispatch(setUserLocation(...))时,实际调用的是组件本地的setUserLocation(useState返回的更新函数),这个函数执行后返回undefined,而Redux要求dispatch的必须是纯对象action,因此触发了该错误。
修复步骤
1. 重命名组件内的useState变量
修改组件内的本地状态变量名,避免和Redux的action creator冲突:
// 替换组件内的useState定义 const [localUserLocation, setLocalUserLocation] = useState(null); // 同步修改setCurrentLocation里的状态更新逻辑 const setCurrentLocation = async () => { try { let { status } = await Location.requestForegroundPermissionsAsync(); if (status !== 'granted') { console.log('Permission to access location was denied'); return; } let location = await Location.getCurrentPositionAsync({}); if (location){ setLocalUserLocation(location) } } catch (error) { console.log('Error occurred while getting location:', error); } }; // 修改监听本地状态的useEffect依赖与判断条件 useEffect(() => { if (localUserLocation && localUserLocation !== "later") { handleLocation(localUserLocation); } }, [localUserLocation]);
2. (可选)简化逻辑,移除冗余本地状态
你不需要用本地状态中转位置信息,可直接在异步函数内dispatch Redux action,减少状态同步步骤:
// 删掉组件内的localUserLocation相关useState // const [localUserLocation, setLocalUserLocation] = useState(null); const setCurrentLocation = async () => { try { let { status } = await Location.requestForegroundPermissionsAsync(); if (status !== 'granted') { console.log('Permission to access location was denied'); return; } let location = await Location.getCurrentPositionAsync({}); if (location){ dispatch(setUserLocation({ location })); } } catch (error) { console.log('Error occurred while getting location:', error); dispatch(setUserLocation({ location: null })); } }; // 同时删掉监听本地状态的useEffect
3. 完善"Set later"逻辑
当前点击"Set later"会传入字符串'later',可根据业务需求调整Redux状态设置:
const handleLocation = (location) => { if (location === null || location === undefined || location === 'later') { dispatch(setUserLocation({ location: null })); // 或设置为'later',依业务需求而定 } else { dispatch(setUserLocation({ location })); } };
额外检查
确保store.js中已正确导入必要的Redux Toolkit方法:
import { combineReducers, configureStore } from '@reduxjs/toolkit';
内容的提问来源于stack exchange,提问作者Emmanuel uzoezie
相关产品推荐
相关产品推荐

