React Native中Redux Saga方法被调用两次如何修复
Redux Saga 重复调用两次问题修复方案
根据你提供的代码,按优先级逐一排查修复以下问题即可:
1. 修复Store配置的中间件注入错误
你当前代码中创建了sagaMiddleware并存入middleware数组,但createStore时没有通过applyMiddleware注入该中间件,会导致saga监听逻辑运行异常。
修正后的配置代码:
import { createStore, applyMiddleware, compose } from 'redux'; import createSagaMiddleware from 'redux-saga'; import rootReducer from '你的reducer路径'; import rootSaga from '你的rootSaga路径'; const configureStore = (): Store<IState> => { const sagaMiddleware = createSagaMiddleware(); // 注册saga中间件到enhancer列表 const enhancers = [applyMiddleware(sagaMiddleware)]; const storeConfig: Store<IState> = createStore( rootReducer, compose(...enhancers) ); sagaMiddleware.run(rootSaga); return storeConfig; };
额外检查
StoreProviderService.init的实现逻辑,确认没有重复执行configureStore,两次初始化store会导致saga watcher被重复注册。
2. 检查rootSaga的watcher注册
打开你的rootSaga文件,确认watchLable没有被重复fork:
- 错误示例(会导致重复触发):
export default function* rootSaga() { yield all([ LableSaga.watchLable(), // 其他业务saga LableSaga.watchLable(), // 重复注册了同一个监听 ]) }
- 同一个watcher只保留一次调用即可。
3. 修复Saga方法内的未定义变量引用
你当前的fetchValueLable存在作用域变量未定义的问题,会抛出引用错误触发异常逻辑:
export function* fetchValueLable(action: IFluxStandardAction<ILables>) { try { // 从action参数中解构payload,不要直接使用未声明的payload变量 const { payload } = action; if (!payload) { return; } const response = yield call(serviceClass.getLables, payload); if (response.success && response.lines != null) { // 传入接口实际返回的数据,不要使用未声明的AvailableLables变量 yield put(Actions.fetchLableSuccess(response.lines)); } } catch (e) { yield put(Actions.fetchLableFailure(e.message)); } }
4. 排查组件层重复Dispatch问题
检查组件中触发fetchLableValue的逻辑:
- 类组件场景:确认
componentDidUpdate中调用action时加了状态判断,不要无差别触发;不要在render函数顶层直接调用action - 函数组件场景:确认
useEffect的依赖数组配置正确,不要把每次渲染都会生成新引用的未缓存值直接放入依赖,避免effect重复执行触发dispatch - 确认没有在多个生命周期/回调中重复调用同一个action。
内容的提问来源于stack exchange,提问作者Kartiikeya
相关产品推荐
相关产品推荐

