服务端Apollo GraphQL Mutation报错:非空字段不能返回空,如何解决?
Hey there! Let's break down that Cannot return null for non-nullable field error you're facing with your Apollo GraphQL user registration flow. This is super common when starting out, and it almost always boils down to a mismatch between your schema definitions and what your resolver functions actually return.
Common Causes & Fixes for Your Scenario
Let's go through the most likely issues based on the code snippets you shared:
Your
createAccountmutation is missing a non-null return type (or your resolver isn't fulfilling it)
Looking at your schema snippet, thecreateAccountmutation cuts off atemail: St...— I'm guessing you intended it to acceptemail: String!as an argument, but you also need to define its return type. If you want it to return the newly created user (which is standard for registration), your mutation should look like:type Mutation { createAccount(name: String!, email: String!): User! }The
User!means your resolver must return a valid User object (not null). If your resolver is returningnull(maybe because you haven't hooked up a database yet, or your test logic isn't generating a user), that's exactly what triggers the error.Your resolver isn't returning a complete User object
Even if you do return something from the resolver, if it's missing one of the non-null fields (id,name,email), GraphQL will throw this error. For testing purposes, you can hardcode a valid User object in your resolver to rule this out:// Example resolver for createAccount const resolvers = { Mutation: { createAccount: (parent, { name, email }) => { // Skip database calls for testing — return a mock user return { id: `test-user-${Date.now()}`, // Generate a unique ID name: name, email: email }; } } };This ensures you're returning all required non-null fields, which should resolve the error if the issue was incomplete data.
Async resolver logic isn't handling promises correctly
If you're using async/await or promises in your resolver (e.g., to save to a database), make sure you're properly returning the resolved value. For example, if you forget toawaita database call, your resolver might return a pending promise instead of a User object — which GraphQL interprets as null.
Quick Test to Confirm
Try running a mutation like this in your GraphQL playground:
mutation { createAccount(name: "Test User", email: "test@example.com") { id name email } }
If you use the mock resolver I shared above, this should return a valid user without errors. If it still throws the error, double-check that your schema's User type doesn't have any typos, and that your resolver is correctly mapped to the createAccount mutation.
内容的提问来源于stack exchange,提问作者Collins Orlando

