Bone rotates weirdly?

https://gyazo.com/5af83cd67f71f3827290dcb989c8795a As you can see here, the bone for some reason flips around weirdly. Why is this? Is there any way I can fix it? I tried pressing alt+r to reset the rotation and then re-pose the bone, but that only made it so that the bone flipped out weirdly on the next keyframe. Are there any other solutions?

looks like a typical case of a gimbal lock

you could fix that by changing that bone rotation type from euler to quaterion.
There is an option in the rigify addon to convert rotation type for the whole animation but I don’t know how good is it.

If you don’t know what a gimbal lock is check the video here:

image
If you are already using quaternions try following steps:
1.Select bone in the red circle
2.Move to the first marked keyframe
3.Flip quaternions (Pose->Flip Quats)
4.Insert keyframe on that bone
5.Repeat these steps for the next keyframes if needed