You have to be careful when shifting under load, or any time there is much torque. You really shouldn't be shifting under any torque.
When I'm cycling on my road bike, I instinctively know exactly when and for how long to ease on the pedals when I shift. Since I am the motor there, I can precisely bring chain tension to near 0, shift completely, then go back into full throttle (sprinting or whatever) - all within about .3 seconds.
Now, when it comes to shifting my ebike - that's another story. It's hard to begin with since I still have the shifter and throttle on the right - need to fix that. But I also had a problem last week when I shifted with the chain spinning at about 120rpms. It tends to slap sideways a bit when shifted at high speed, so that time it hit the motor drivetrain to the left, and caught on it. Then it got jammed between the two. I'm going to remount my front derailer just to act as a chain guard.
But back to your case - it is widely known that you shouldn't shift under load. It will vastly increase your chances of breaking the chain. That reminds me - last night I did a real hard sprint up a hill last night on my road bike. The gear wasn't sitting perfectly and it jumped I think - broke my chain. It's probably the only the 2nd time I've broken a chain in 60,000 pedal miles. And I sprint like a madman all the time. The only reason it broke was because it jumped. I was lucky, 3 other cyclists saw me and stopped to help, and I was lucky to have my master link on me.