Free actions cannot be taken outside your turn, and the rules don’t allow for any exceptions to this—but there are cases where I feel exceptions should be.
For example, many features allow for free-action follow-ups to one’s attacks. Grappling,1 for example, basically relies upon it. If you cannot take a free action outside of your turn, it means that attacks of opportunity cannot use these features, even when they can trigger them. I think this is poor for the game, and so I allow these kinds of free actions to occur when triggered, even outside one’s turn.
Likewise, free actions necessary to use reactive abilities—e.g. attacks of opportunity and immediate actions—are something I routinely allow. For example, this answer discusses letting go of a polearm to punch someone.1 This is a very analogous situation.
I would strongly recommend allowing a caster to do this. Frankly, banning it feels like a very un-fun “gotcha” that just doesn’t add anything to the game. The spellcaster could have just held the quarterstaff in one hand the whole time—to say “ah, you forgot to say you were letting one hand off of the quarterstaff after you finished attacking last turn, so no immediate-action spell for you!” is just... not great GMing, in my opinion. That kind of thing might well make me reevaluate whether or not I was actually interested in playing this game.
So just let them let go for the spell, as if they’d let go at the end of their turn. Officially, they “should have” missed out on the opportunity to take attacks of opportunity, but most spellcasters aren’t very good at those anyway. So letting them have both those and immediate-action spells is fine. And if they’ve actually built for attacks of opportunity with their quarterstaff, I see no reason to throw a wrench in their plans—that’s not exactly a high-power approach that I’d feel needs to be toned down.
- Both of these links are to questions about D&D 3.5e, not Pathfinder, but the relevant rules in each case are the same.