Ошибка при использовании сагы редукса, take (patternOrChannel): аргумент 8 не является допустимым каналом или допустимым шаблоном - PullRequest
0 голосов
/ 05 октября 2018

Я пытаюсь использовать библиотеку SAGS для записи некоторых действий, но у меня возникает эта ошибка при запуске приложения:

index.js: 2178 uncaught в rootSaga в rootSaga в projectSagaat watchFetchRequest at takeEvery Ошибка: take (patternOrChannel): аргумент 8 не является допустимым каналом или допустимым шаблоном при take (http://localhost:3000/static/js/bundle.js:84689:9) в takeEvery (http://localhost:3000/static/js/bundle.js:85993:94) в createTaskIterator (http://localhost:3000/static/js/bundle.js:85179:17) в runForkEffect)(http://localhost:3000/static/js/bundle.js:85583:24) в runEffect (http://localhost:3000/static/js/bundle.js:85468:872) в следующий (http://localhost:3000/static/js/bundle.js:85348:9) в proc (http://localhost:3000/static/js/bundle.js:85303:3) в runForkEffect (http://localhost:3000/static/js/bundle.js:85587:19) в runEffect (http://localhost:3000/static/js/bundle.js:85468:872) при http://localhost:3000/static/js/bundle.js:85677:14 при Array.forEach () при runAllEffect (http://localhost:3000/static/js/bundle.js:85676:10) при runEffect (http://localhost:3000/static/js/bundle.js:85468:413) при следующем (http://localhost:3000/static/js/bundle.js:85348:9) при выполнении (* 1031)* в runForkEffect (http://localhost:3000/static/js/bundle.js:85587:19) в runEffect (http://localhost:3000/static/js/bundle.js:85468:872) в http://localhost:3000/static/js/bundle.js:85677:14 в Array.forEach () в runAllEffect (http://localhost:3000/static/js/bundle.js:85676:10) в runEffect (http://localhost:3000/static/js/bundle.js:85468:413))в следующем (http://localhost:3000/static/js/bundle.js:85348:9) в процессе (http://localhost:3000/static/js/bundle.js:85303:3) в RunSaga (http://localhost:3000/static/js/bundle.js:85858:76) в Object ../ src / store / ReduxRoot.tsx (http://localhost:3000/static/js/bundle.js:95823:16) в webpack_require (http://localhost:3000/static/js/bundle.js:679:30) в fn (http://localhost:3000/static/js/bundle.js:89:20) в Object ../ src / index.tsx (http://localhost:3000/static/js/bundle.js:95325:75) в webpack_require (http://localhost:3000/static/js/bundle.js:679:30) в fn (http://localhost:3000/static/js/bundle.js:89:20) в Object.0 (http://localhost:3000/static/js/bundle.js:96424:18) в webpack_require (http://localhost:3000/static/js/bundle.js:679:30) в ./node_modules/@babel/runtime/helpers/arrayWithoutHoles.js.module.exports (http://localhost:3000/static/js/bundle.js:725:37) at http://localhost:3000/static/js/bundle.js:728:10

Это код саги:

import { all, call, fork, put, takeEvery } from 'redux-saga/effects';
import {  ActionType, Action, SearchCriteria } from '../model/types';
import { searchProjectsError, searchProjectsCompleted } from '../actions/projects';
import { API_URL } from '../../config';
// import axios from 'axios';

function callApi(method: string, url: string, path: string, data?: any) {
    return fetch(url  + path, {
      method,
      headers: {'Content-Type': 'application/json; charset=utf-8', 'Access-Control-Allow-Origin': '*'},
      body: JSON.stringify(data)
    }).then(res => res.json());
  }

// Here we use `redux-saga` to trigger actions asynchronously. `redux-saga` uses something called a
// "generator function", which you can read about here:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*

function* handleFetch(action: Action<SearchCriteria>) {
  try {
    // To call async functions, use redux-saga's `call()`.
    const res = yield call(callApi, 'get', API_URL , '/api/DocumentLoader/GetProjects/', action.payload);

    if (res.error) {
      yield put(searchProjectsError(res.error));
    } else {
      yield put(searchProjectsCompleted(res));
    }
  } catch (err) {
    if (err instanceof Error) {
      yield put(searchProjectsError(err.stack!));
    } else {
      yield put(searchProjectsError('An unknown error occured.'));
    }
  }
}

// This is our watcher function. We use `take*()` functions to watch Redux for a specific action
// type, and run our saga, for example the `handleFetch()` saga above.
function* watchFetchRequest() {
  yield takeEvery(ActionType.SEARCH_PROJECTS, handleFetch); // I think the error is here
}

// We can also use `fork()` here to split our saga into multiple watchers.
function* projectSaga() {
  yield all([fork(watchFetchRequest)]);
}

export default projectSaga;

Я уже пытался найти ответ здесь, в SO, но единственное, что я смог найтибыл этот пост , но ActionType был экспортирован.Я думаю, что проблема с параметром handleFetch function

Это действие:

export function searchProjects(criterias: SearchCriteria): Action<SearchCriteria> {
    return {
        type: ActionType.SEARCH_PROJECTS,
        payload: criterias
    };
}

Другая вещь, которая может быть, может быть, я сделал что-то не так в то время, чтобы составитьпромежуточное программное обеспечение saga:

const sagaMiddleware = createSagaMiddleware();

var middleware = applyMiddleware(logger, thunk, sagaMiddleware);

if (process.env.NODE_ENV === 'development') {
    middleware = composeWithDevTools(middleware);
}

// Here we use `redux-saga` to trigger actions asynchronously. `redux-saga` uses something called a
// "generator function", which you can read about here:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*
export function* rootSaga() {
    yield all([fork(projectSaga)]);
  }
// running the root saga, and return the store object.
 sagaMiddleware.run(rootSaga);

Я также попытался удалить параметр действия из handleFetch, и ошибка все еще происходит

Ответы [ 2 ]

0 голосов
/ 05 октября 2018

Я нашел, в чем была ошибка, проблема заключалась в определении ActionType enum.Это было без назначения строкового значения для каждого действия.

export const enum ActionType {

// Projects
SEARCH_PROJECT,
SEARCH_PROJECTS_COMPLETED,
SEARCH_PROJECTS_ERROR,

}

Это решило проблему:

export const enum ActionType {

// Projects
SEARCH_PROJECTS= '@@projects/SEARCH_PROJECTS',
SEARCH_PROJECTS_COMPLETED= '@@projects/SEARCH_PROJECTS_COMPLETED',
SEARCH_PROJECTS_ERROR= '@@projects/SEARCH_PROJECTS_ERROR',

}
0 голосов
/ 05 октября 2018

Единственная возможная ошибка может быть следующей:

Проверьте, импортировали ли вы здесь {ActionType} объект из файла моделей, в котором вы определили свои константы.

export function searchProjects(criterias: SearchCriteria): 
    Action<SearchCriteria> {
    return {
        type: ActionType.SEARCH_PROJECTS,
        payload: criterias
    };
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...