首页 > 解决方案 > 'yield' 表达式只允许在生成器主体中使用

问题描述

redux-saga用来获取服务器 api 数据。我的问题是我正在尝试设计以下代码。

但是yield put(get01Action(members));,被注释掉的有以下语法错误。

A 'yield' expression is only allowed in a generator body.

我不知道如何管理它。

import '@babel/polyfill';
import { fork, take, put } from 'redux-saga/effects';
import axios from "axios";

export function* rootSaga(){
    yield fork(fetch01);
    yield fork(fetch02);
}

function* fetch01() {
    while (true){
        yield take('FETCH01_REQUEST');
        axios.get('/api/members')
            .then(function (response) {
                // handle success
                let members = response.data.data;
                // yield put(get01Action(members));
            })
            .catch(function (error) {
                // handle error
                console.log(error);
            })
            .finally(function () {
                // always executed
            });
    }
}
function* fetch02() {
    ....
}

function get01Action(members){
    return {
        type: 'GET_MEMBERS',
        member_id: 0,
        members: members
    }
}

请给我一些建议。

谢谢。

标签: reactjsreduxredux-saga

解决方案


因为您的发电机fetch01是同步的,但您正在等待Promise解决。

yield不能包裹在生成器以外的其他函数中。

您可以制作生成器async,如下所示:

export async function* rootSaga(){
    yield await fork(fetch01);
    yield fork(fetch02);
}
async function* fetch01() {
    while (true) {
        yield take('FETCH01_REQUEST');
        try {
            const response = await axios.get('/api/members');
            // handle success
            let members = response.data.data;
            yield put(get01Action(members));
        } catch (error) {
            // handle error
            console.log(error);
        } finally {
            // always executed
        }
    }
}

推荐阅读