首页 > 解决方案 > 异步函数未执行

问题描述

我正在尝试在 Redux 操作中从 SQL 服务器获取数据。我的问题是,异步函数内部的东西绝对没有运行。'try' 和'catch' 分支都不是。

export function fetchMessages() {
    console.log("Fetching messages...");


    let tempDisp = async dispatch => {
        //This way we can show a loading screen
        console.log("Before try catch")
        dispatch(fetchMessagesBegin());
        try {
            const res = await fetch('http://185-220-204-106.cloud-xip.io:5000/messages/all');
            const json = await res.json();
            console.log("json is: ", json);
            console.log("The json object:", json);
            dispatch(fetchMessagesSuccess(json));
            return json.messages;
        }
        catch (error) {
            dispatch(fetchMessagesFailure(error));
            console.log("Error: ", error);
        }
    };

    console.log("The tempDisp is: ",tempDisp);
    return tempDisp;
}

我得到的控制台输出是

Fetching messages... main.chunk.js:292:11
The tempDisp is: function tempDisp()

因此,在异步运行之前的 console.log,在 try...catch 没有运行之前,并且 Error 分支也没有运行。我正在尝试从 useEffect() 调用 fetchMessages,但我也在渲染 React 应用程序之前尝试过,结果相同。我无法弄清楚是什么原因造成的。任何帮助表示赞赏。

更新

读完这个帖子后,我像这样重写了我的代码:

export const fetchMessages = messages => async (dispatch) => {
    //This way we can show a loading screen
    console.log("Before try catch");
    dispatch(fetchMessagesBegin());
    try {
        const res = await fetch('http://185-220-204-106.cloud-xip.io:5000/messages/all');
        const json = await res.json();
        console.log("json is: ", json);
        //We might not have a top level container, like 'messages'
        console.log("The json object:", json);
        dispatch(fetchMessagesSuccess(json));
        //return json.messages;
    }
    catch (error) {
        dispatch(fetchMessagesFailure(error));
        console.log("Error: ", error);
    }
}

它仍然无法正常工作,而且我再也没有任何 console.logs 了。

更新 这是我调用 fetchMessages 的地方:

function App({isLoggedIn}) {
  let testingOnly = ["hello"];

  useEffect(() => {
    testingOnly = fetchMessages();

    console.log(isLoggedIn);
  });

[... React return ...]



const mapStateToProps = state => ({
    isLoggedIn: state.isLoggedIn,
    isServerError: state.isServerError,
    serverError: state.serverError,
    loginAttempt: state.loginAttempt,
    messages: state.messages
});

export default connect(mapStateToProps)(App);

标签: reactjsreduxasync-awaittry-catch

解决方案


问题是,我没有安装 redux-thunk。

import thunk from 'redux-thunk';

那么你需要添加中间件来存储

let store = createStore(reducer, applyMiddleware(thunk));

在此之后,它起作用了。


推荐阅读