Redux-saga:如何停止或取消任务链?

Redux-saga: How to stop or cancel task chain?

有异步递增 saga,它在 3 秒后递增计数器

function* incrementAsync() {
    yield call(delay, 3000);
    yield put(counterIncrement());
}

function* incrementAsyncWatcher() {
    yield takeEvery(ASYNC_INCREMENT, incrementAsync);
}

function* incrementCounterSaga() {
    yield fork(incrementAsyncWatcher);
}

const task = sagaMiddleware.run(incrementCounterSaga);

然后我试着阻止这个传奇

task.cancel();

store.dispathch({ type: ASYNC_INCREMENT });

但 3 秒后发现 saga 仍在运行!

如何结束这场传奇?

我发现显式取消任务非常具有挑战性,因为您必须传递和管理任务对象。

相反,我认为这样的模式有效:

function* incrementAsyncWatcher() {
    yield takeLatest(ASYNC_INCREMENT, incrementAsync);
}

takeLatest 将取消任务,而 takeEvery 创建一个新任务。

您还可以为 race 查找 docs 以隐式取消