AWS Amplify GraphQL异常:自动生成Mutations无法写入DynamoDB
Hey there! Let's break down why your Amplify mutations are failing while queries work perfectly—this is usually a small oversight, so let's tackle it step by step.
Most Likely Culprit: Form Default Submit Behavior
The biggest red flag here is that your network trace shows no POST request being sent, paired with the "Request aborted" error. This almost always happens because your form is triggering a full page refresh before the mutation can complete.
When you submit a form in React without preventing the default browser behavior, the browser will immediately reload the page—this cancels any pending API calls (hence the "aborted" error) before they even get sent out.
Fix: Add event.preventDefault() to Your Submit Handler
Update your handleSubmit function to stop the form from reloading the page:
async function handleSubmit (event) { // Critical: Stop the form from refreshing the page event.preventDefault(); try { console.log('Called our API - top'); // Fixed the typo here too: "catetory" → "category" const categoryDetails = { description: 'My new category' } const returnedCategory = await API.graphql(graphqlOperation(createCategory, { input: categoryDetails})); console.log('Called our API', returnedCategory); } catch (err) { console.log('error creating category', err); } }
Also, notice I fixed a small typo in your description text (catetory → category)—it wasn't causing the error, but it's good to clean up for consistency.
Quick Additional Checks (Just to Rule Out Edge Cases)
Since your queries work, most of your Amplify setup is correct, but let's confirm a couple more things:
- Verify your
aws-exports.js: Double-check thataws_appsync_graphqlEndpointis a valid HTTPS URI (no typos like missinghttps://or extra characters). Queries wouldn't work if this was wrong, but it's worth a quick glance. - Confirm Schema Permissions: Your auth rules look solid (public create access enabled for dev), so permissions shouldn't be blocking the mutation. But if you later restrict access, make sure your authenticated user has the right group or permissions.
- Check Auth State: If you switch away from public access later, ensure
Auth.currentAuthenticatedUser()returns a valid user before running mutations. For now, though, your public access should bypass this requirement.
Why This Works
By adding event.preventDefault(), you're telling the browser not to do its default form submit action (page reload). This lets your async mutation call complete normally, and you should start seeing the POST request in your network tab, along with the created category data in your console.
Give this fix a try—it's the most common solution for this exact scenario!
内容的提问来源于stack exchange,提问作者Broom

