React报错:Objects are not valid as a React child问题排查求助
解决React中"Invariant Violation: Objects are not valid as a React child"错误
嘿,我来帮你拆解下这个问题的核心原因:你用async/await的版本报错,本质是直接把Promise对象作为payload传给了ADD_NOTE的action,而非等待Promise完成后拿到它的实际结果。
先看你报错的asyncTest1代码:
const asyncTest1= async() => { try { noteAction({ type: SET_LOADING, payload: true }); const response = new Promise((resolve, reject) => { setTimeout(() => { resolve('Async Test Load'); }, 3000); }); // 这里的response是Promise实例,不是resolve后的字符串! const adding = noteAction({ type: ADD_NOTE, payload: response }); const setLoadingFalse = noteAction({ type: SET_LOADING, payload: false }); const result = await Promise.all([response, adding, setLoadingFalse]); return result; } catch (e) { console.log(e); } };
这段代码里,你创建了response这个Promise,但没有等待它resolve就直接把它传给了ADD_NOTE的action。当React后续尝试渲染这个payload时,它看到的是一个带有_40、_65、_55、_72这些内部属性的Promise对象——而React无法直接渲染对象类型的子元素,所以抛出了那个错误。
再看你正常运行的asyncTest2,它是在Promise的then方法里,拿到resolve后的response(也就是字符串'Async Test Load')之后才传给action,所以payload是合法的可渲染值,自然不会报错。
修正后的async/await版本
只需要先等待response resolve拿到实际结果,再传给ADD_NOTE的action就可以了:
const asyncTest1= async() => { try { noteAction({ type: SET_LOADING, payload: true }); // 先等待Promise resolve,拿到实际的字符串结果 const response = await new Promise((resolve, reject) => { setTimeout(() => { resolve('Async Test Load'); }, 3000); }); // 现在response是字符串,不是Promise对象了 const adding = noteAction({ type: ADD_NOTE, payload: response }); const setLoadingFalse = noteAction({ type: SET_LOADING, payload: false }); await Promise.all([adding, setLoadingFalse]); return response; } catch (e) { console.log(e); } };
或者如果你想保留Promise.all的写法,也可以这样调整:
const asyncTest1= async() => { try { noteAction({ type: SET_LOADING, payload: true }); const responsePromise = new Promise((resolve, reject) => { setTimeout(() => { resolve('Async Test Load'); }, 3000); }); // 先等Promise完成,拿到实际值 const response = await responsePromise; const adding = noteAction({ type: ADD_NOTE, payload: response }); const setLoadingFalse = noteAction({ type: SET_LOADING, payload: false }); const result = await Promise.all([adding, setLoadingFalse]); return result; } catch (e) { console.log(e); } };
核心逻辑就是确保传给ADD_NOTE的payload是Promise resolve后的实际值,而非Promise对象本身。
内容的提问来源于stack exchange,提问作者ukiyakimura
相关产品推荐
相关产品推荐

