That's happened to me. Especially when sleeping. It's actually only happened to me once outside of bed.
From what I understand, you can't keep your leg bent. Straighten it out and keep your foot at a 90-degree angle to your calf. It may be hard to keep yourself from twitching, but you'll get the hang of it.