【问题标题】:Async function is not executing异步函数未执行
【发布时间】:2020-06-22 21:46:39
【问题描述】:

我正在尝试在 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 应用程序之前尝试过,结果相同。我无法弄清楚是什么原因造成的。任何帮助表示赞赏。

更新

阅读this thread后,我重写了我的代码:

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);

【问题讨论】:

  • 您将 async/await 存储在变量 tempDisp 中,然后将其返回。由于它是一个函数,因此您现在返回对该函数的引用,现在您必须调用它。请显示您在哪里使用fetchMessages

标签: reactjs redux async-await try-catch


【解决方案1】:

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

import thunk from 'redux-thunk';

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

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

在这之后,它起作用了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多